用SXSSFWorkbook導出50萬條數據到本地Excel文件(簡單實現例子)

不廢話,上代碼:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BigDataExcelUtils {

    public static void writeBigData() throws IOException {
        long startTime = System.currentTimeMillis();    //獲取開始時間,單位毫秒
        FileInputStream inputStream = new FileInputStream("C:\\temp\\template.xls");
        XSSFWorkbook wb_template = new XSSFWorkbook(inputStream);
        inputStream.close();

        SXSSFWorkbook wb = new SXSSFWorkbook(wb_template);
        wb.setCompressTempFiles(true);
        SXSSFSheet sh = (SXSSFSheet) wb.getSheetAt(0);
        sh.setRandomAccessWindowSize(100);// keep 100 rows in memory, exceeding rows will be flushed to disk,每次加載到內存100條
        for(int rowNum = 0; rowNum < 500000; rowNum++){ //500000爲行數
            Row row = sh.createRow(rowNum);
            for(int cellNum = 0; cellNum < 10; cellNum++){ //10爲列數
                Cell cell = row.createCell(cellNum);
                String address = new CellReference(cell).formatAsString();
                cell.setCellValue(address);
            }
        }
        FileOutputStream outFile = new FileOutputStream("C:\\temp\\tempsxssf.xlsx");
        wb.write(outFile);
        outFile.close();
        wb.dispose();// dispose of temporary files backing this workbook on disk
        long endTime=System.currentTimeMillis(); //獲取開始時間,單位毫秒
        long duration = endTime - startTime;
        System.out.println("程序運行時長:" + Double.valueOf(duration)/1000 + "秒");
    }

    public static void main(String[] args) throws Throwable {
        writeBigData();
    }
}

程序運行時間約25秒。當然,實際業務處理還有別的地方消耗時間。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章