poi实现多线程导出Excel分sheet(二)

昨天文章讲了讲了如何单线程导出Excel今天就简单写一下如何多线程导出Excel

废话不多说直接上代码

简单的多线程类

package com.learn.mul;

import com.learn.entity.Student;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author summer
 * @date 2022-05-11  13:01
 */
public class MoreThread implements  Runnable{

    private List<Student> studentList;
    private Sheet sheet;
    private CountDownLatch countDownLatch;

    public MoreThread(List<Student> studentList, Sheet sheet, CountDownLatch countDownLatch) {
        this.studentList = studentList;
        this.sheet = sheet;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
        try {
            exportMore();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public void exportMore() throws IllegalAccessException {
        Iterator<Student> iterator = studentList.iterator();
        Field[] fields = Student.class.getDeclaredFields();
        int startIndex = 0;
        if(startIndex == 0){
            Row row = sheet.createRow(startIndex);
            for (int i = 0; i < fields.length; i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(fields[i].getName());
            }
            startIndex++;
        }
        while(iterator.hasNext()){
            Student student = iterator.next();
            Row row = sheet.createRow(startIndex);
            for (int i = 0; i < fields.length; i++) {
                Cell cell = row.createCell(i);
                Field field = fields[i];
                field.setAccessible(true);
                cell.setCellValue(String.valueOf(field.get(student)));
            }
            startIndex++;
        }
        countDownLatch.countDown();
    }


}

在上篇文章中Main方法写多线程导出方法

public static void exportDataMore(List<Student> studentList, int threadNum) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook();
//        Field field = workbook.getClass().getDeclaredField("sharedStringSource");
//        field.setAccessible(true);
//        field.set(workbook,new CustomSharedStringsTable());

        int count = studentList.size();
        int avgCount = (int) Math.floor(count / threadNum);
        int modeCount = count % threadNum;

        int start = 0;
        int end = 0;
        CountDownLatch countDownLatch = new CountDownLatch(threadNum);
        for (int i = 0; i < threadNum; i++) {
            start = i * avgCount;
            if (i == threadNum - 1) {
                end = (i + 1) * avgCount + modeCount;
            } else {
                end = (i + 1) * avgCount;
            }
            List<Student> students = studentList.subList(start, end);
            Sheet sheet = workbook.createSheet();

            new Thread(new MoreThread(students,sheet,countDownLatch),"线程:"+i).start();
        }
        countDownLatch.await();
        FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\Summer\\Desktop\\poi\\student-more.xlsx"));

        workbook.write(fos);

    }

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java POI提供了一种多线程导出Excel的方式,可以提高导出效率。 以下是一个简单的示例代码: ```java public class ExcelExportThread extends Thread { private Workbook workbook; private OutputStream outputStream; public ExcelExportThread(Workbook workbook, OutputStream outputStream) { this.workbook = workbook; this.outputStream = outputStream; } @Override public void run() { try { workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } public class ExcelExporter { public static void export(List<List<Object>> dataList, int sheetSize, OutputStream outputStream) { Workbook workbook = new XSSFWorkbook(); int dataSize = dataList.size(); int sheetNum = dataSize % sheetSize == 0 ? dataSize / sheetSize : dataSize / sheetSize + 1; CountDownLatch latch = new CountDownLatch(sheetNum); for (int i = 0; i < sheetNum; i++) { int start = i * sheetSize; int end = Math.min(start + sheetSize, dataSize); List<List<Object>> subList = dataList.subList(start, end); ExcelExportThread thread = new ExcelExportThread(createSheet(workbook, subList), outputStream); thread.start(); thread.setUncaughtExceptionHandler((t, e) -> { // 异常处理 }); thread.setContextClassLoader(null); thread.setName("ExcelExportThread-" + i); thread.setPriority(Thread.NORM_PRIORITY); thread.setDaemon(false); thread.start(); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private static Sheet createSheet(Workbook workbook, List<List<Object>> dataList) { Sheet sheet = workbook.createSheet(); int rowIndex = 0; for (List<Object> rowData : dataList) { Row row = sheet.createRow(rowIndex++); int colIndex = 0; for (Object cellData : rowData) { Cell cell = row.createCell(colIndex++); cell.setCellValue(cellData.toString()); } } return sheet; } } ``` 该示例中,ExcelExporter类提供了一个静态方法export,用于导出Excel。该方法接收三个参数:数据列表、每个Sheet的最大行数、输出流。 export方法首先创建一个新的Workbook实例,然后根据每个Sheet的最大行数将数据列表拆为多个子列表,并创建ExcelExportThread实例进行导出。每个ExcelExportThread实例会创建一个Sheet,并将数据写入Sheet中。多个线程同时导出,提高了导出效率。 在ExcelExportThread的run方法中,使用Workbook的write方法将数据写入输出流,导出Excel文件。导出完成后,关闭输出流。 在示例中,使用了CountDownLatch来等待所有线程导出完成。如果线程中出现异常,可以在ExcelExportThread的setUncaughtExceptionHandler方法中进行处理。其他线程属性设置可以根据实际情况进行调整。 需要注意的是,由于多线程导出Excel可能会占用大量的内存和CPU资源,可能会导致系统负载过高,因此需要根据实际情况进行调整。同时,多线程导出Excel也可能会导致导出结果的顺序发生变化,需要注意处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜欢编程的夏先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值