帮我用java 写一个 多线程实现Excel 导出的案例
时间: 2024-03-09 14:49:14 浏览: 139
JavaExcel导出示例
好的,以下是一个多线程实现Excel导出的简单案例:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExporter implements Runnable {
private List<List<Object>> data;
private String filename;
public ExcelExporter(List<List<Object>> data, String filename) {
this.data = data;
this.filename = filename;
}
@Override
public void run() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
int rowNum = 0;
for (List<Object> rowData : data) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field : rowData) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
} else if (field instanceof Double) {
cell.setCellValue((Double) field);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(new File(filename));
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
List<List<Object>> data1 = List.of(
List.of("Alice", 25),
List.of("Bob", 30),
List.of("Charlie", 35)
);
List<List<Object>> data2 = List.of(
List.of("David", 40),
List.of("Emily", 45),
List.of("Frank", 50)
);
List<List<Object>> data3 = List.of(
List.of("Grace", 55),
List.of("Henry", 60),
List.of("Ivy", 65)
);
ExecutorService executorService = Executors.newFixedThreadPool(3);
executorService.execute(new ExcelExporter(data1, "file1.xlsx"));
executorService.execute(new ExcelExporter(data2, "file2.xlsx"));
executorService.execute(new ExcelExporter(data3, "file3.xlsx"));
executorService.shutdown();
}
}
```
在这个案例中,我们定义了一个 ExcelExporter 类,该类实现了 Runnable 接口,即可实现多线程。在类的构造函数中接受数据和文件名参数,并在 run() 方法中使用 Apache POI 库将数据导出到 Excel 文件中。在主函数中,我们创建了三个 ExcelExporter 对象并使用 ExecutorService 管理线程池,最后等待所有线程完成工作。这个案例中导出的 Excel 文件可以分别命名为 file1.xlsx,file2.xlsx 和 file3.xlsx。
阅读全文