java 用安全的多线程写导出多个sheet页Excel功能 带有代码注释
时间: 2024-05-06 22:18:29 浏览: 93
java导出包含多个sheet的Excel代码示例
以下是一个使用Java多线程导出多个sheet页的Excel示例,带有代码注释:
```java
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
public class ExcelExportService {
// 定义线程池
private ExecutorService executorService;
// 定义导出数据列表
private List<List<Object[]>> dataList = new ArrayList<>();
// 定义每个sheet页的标题
private List<String> sheetTitles = new ArrayList<>();
// 构造函数,初始化线程池
public ExcelExportService(int threadCount) {
executorService = Executors.newFixedThreadPool(threadCount);
}
// 添加导出数据
public void addData(List<Object[]> data, String sheetTitle) {
dataList.add(data);
sheetTitles.add(sheetTitle);
}
// 导出Excel文件
public void exportExcel(String filePath) throws Exception {
// 创建工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中对齐
// 创建字体
HSSFFont font = workbook.createFont();
font.setBold(true); // 加粗
cellStyle.setFont(font);
// 循环生成每个sheet页
for (int i = 0; i < dataList.size(); i++) {
final int sheetIndex = i;
executorService.execute(new Runnable() {
@Override
public void run() {
// 创建sheet页
HSSFSheet sheet = workbook.createSheet(sheetTitles.get(sheetIndex));
// 获取数据
List<Object[]> data = dataList.get(sheetIndex);
// 循环生成每行数据
for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
Object[] rowData = data.get(rowIndex);
HSSFRow row = sheet.createRow(rowIndex);
// 循环生成每个单元格
for (int cellIndex = 0; cellIndex < rowData.length; cellIndex++) {
row.createCell(cellIndex).setCellValue(rowData[cellIndex].toString());
}
}
// 设置标题行样式
sheet.getRow(0).setRowStyle(cellStyle);
}
});
}
// 等待所有线程执行完毕
executorService.shutdown();
while (!executorService.isTerminated()) {
Thread.sleep(100);
}
// 写入文件
FileOutputStream fos = new FileOutputStream(filePath);
workbook.write(fos);
fos.close();
}
}
```
使用方法:
```java
// 创建导出服务
ExcelExportService exportService = new ExcelExportService(10); // 创建10个线程的线程池
// 添加导出数据
List<Object[]> data1 = new ArrayList<>();
data1.add(new Object[] {"姓名", "年龄", "性别"});
data1.add(new Object[] {"张三", 18, "男"});
exportService.addData(data1, "学生");
List<Object[]> data2 = new ArrayList<>();
data2.add(new Object[] {"名称", "价格", "库存"});
data2.add(new Object[] {"手机", 1999, 50});
exportService.addData(data2, "商品");
// 导出Excel文件
exportService.exportExcel("D:\\test.xls");
```
阅读全文