poi 匯出大資料量資料到excel. 百萬資料
阿新 • • 發佈:2019-01-30
利用poi匯出百萬資料
public void print() throws IOException{ Long startTime = System.currentTimeMillis(); HpaDAO oDao = (HpaDAO) this.getDao("daoHpa"); List<Hpa> dataList = oDao.find("from Hpa o"); Workbook wb = new SXSSFWorkbook(1000); //重點在這句 .每1000條寫一個臨時檔案 Sheet sheet = wb.createSheet("我的第一個工作簿"); Row nRow =null; Cell nCell = null; int rowNo = 0; short colNo = 0; for(Hpa hpa : dataList){ colNo = 0; nRow = sheet.createRow(rowNo++); nCell = nRow.createCell(colNo++); nCell.setCellValue(hpa.getId()); nCell = nRow.createCell(colNo++); nCell.setCellValue(hpa.getBreast()); nCell = nRow.createCell(colNo++); nCell.setCellValue(hpa.getAdipocytes()); nCell = nRow.createCell(colNo++); nCell.setCellValue(hpa.getNegative()); nCell = nRow.createCell(colNo++); nCell.setCellValue(hpa.getStaining()); nCell = nRow.createCell(colNo++); nCell.setCellValue(hpa.getSupportive()); if(rowNo%1000==0){ System.out.println(rowNo); } } //生成excel檔案 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//生成流物件 wb.write(byteArrayOutputStream); //工具類 , 封裝彈出下載框: String outFile = "bigdata.xls"; DownloadBase downloadBase = new DownloadBase(); HttpServletResponse response = ServletActionContext.getResponse(); downloadBase.download(byteArrayOutputStream, response, outFile); Long stopTime = System.currentTimeMillis(); System.out.println((stopTime-startTime)+"ms"); }
本人實測104萬的資料 用時18秒到 excel
注意點:
Workbook wb = new SXSSFWorkbook(1000); //重點在這句 .每1000條寫一個臨時檔案
匯入jar包:
核心包:
poi-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
依賴包:
commons-beanutils-1.7.0.jar
commons-collections-3.0.jar
commons-lang-2.0.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
standard-1.0.2.jar
stax-api-1.0.1.jar
xmlbeans-2.3.0.jar
mysql-connector-java-5.1.10-bin.jar
junit-4.8.2.jar