java poi多线程在同一张表中插入数据
时间: 2023-10-18 07:16:54 浏览: 85
Java多线程读取大文本文件并批量插入MongoDB的实战代码
5星 · 资源好评率100%
在Java POI中,可以使用多线程在同一张表中插入数据。下面是一个示例代码:
```
import java.io.FileOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class MultiThreadedExcelWriter {
private static final String FILE_NAME = "test.xlsx";
private static final int NUMBER_OF_THREADS = 10;
private static final int ROWS_PER_THREAD = 100;
public static void main(String[] args) throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
final int startIndex = i * ROWS_PER_THREAD;
executorService.execute(() -> {
for (int j = startIndex; j < startIndex + ROWS_PER_THREAD; j++) {
Row row = sheet.createRow(j);
Cell cell1 = row.createCell(0);
cell1.setCellValue("Value " + j);
Cell cell2 = row.createCell(1);
cell2.setCellValue("Thread " + Thread.currentThread().getId());
}
});
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
workbook.write(outputStream);
workbook.close();
outputStream.close();
}
}
```
这个示例代码会创建一个包含10个线程的线程池,每个线程会插入100行数据到同一个表中。注意要等待所有线程完成后再保存文件。
阅读全文