JavaPOI在解決導出大數據量的處理方案(導出數據在一百萬行左右)

Excel2003版最大行數是65536行。Excel2007開始的版本最大行數是1048576行。

Excel2003的最大列數是256列,2007以上版本是16384列。

 

poi導出excel,不使用模板的

http://happyqing.iteye.com/blog/2075985

 

xls格式導出使用HSSFWorkbook,(這個暫時沒有好辦法)

 

xlsx格式導出以前使用XSSFWorkbook,可以使用新的SXSSFWorkbook(poi3.8+)

 

Workbook wb = new SXSSFWorkbook(1000); //大於1000行時會把之前的行寫入硬盤

 

Row,Cell還跟之前的一樣

 

官方樣例

http://poi.apache.org/spreadsheet/how-to.html#sxssf

Java代碼  收藏代碼
  1. import junit.framework.Assert;  
  2. import org.apache.poi.ss.usermodel.Cell;  
  3. import org.apache.poi.ss.usermodel.Row;  
  4. import org.apache.poi.ss.usermodel.Sheet;  
  5. import org.apache.poi.ss.usermodel.Workbook;  
  6. import org.apache.poi.ss.util.CellReference;  
  7. import org.apache.poi.xssf.streaming.SXSSFWorkbook;  
  8.   
  9.     public static void main(String[] args) throws Throwable {  
  10.         SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk  
  11.         Sheet sh = wb.createSheet();  
  12.         for(int rownum = 0; rownum < 1000; rownum++){  
  13.             Row row = sh.createRow(rownum);  
  14.             for(int cellnum = 0; cellnum < 10; cellnum++){  
  15.                 Cell cell = row.createCell(cellnum);  
  16.                 String address = new CellReference(cell).formatAsString();  
  17.                 cell.setCellValue(address);  
  18.             }  
  19.   
  20.         }  
  21.   
  22.         // Rows with rownum < 900 are flushed and not accessible  
  23.         for(int rownum = 0; rownum < 900; rownum++){  
  24.           Assert.assertNull(sh.getRow(rownum));  
  25.         }  
  26.   
  27.         // ther last 100 rows are still in memory  
  28.         for(int rownum = 900; rownum < 1000; rownum++){  
  29.             Assert.assertNotNull(sh.getRow(rownum));  
  30.         }  
  31.           
  32.         FileOutputStream out = new FileOutputStream("/temp/sxssf.xlsx");  
  33.         wb.write(out);  
  34.         out.close();  
  35.   
  36.         // dispose of temporary files backing this workbook on disk  
  37.         wb.dispose();  
  38.     }  

 

 值得注意的是SXSSFWorkbook只能寫不能讀。但是往往我們需要向一個Excel模版裏導出數據,這樣才更好提前定義裏面的格式和vba代碼。

這裏就需要使用SXSSFWorkbook的另外一個構造函數:

SXSSFWorkbook(XSSFWorkbook workbook)
Construct a workbook from a template.

 通過XSSFWorkbook來讀取模版,然後用SXSSFWorkbook來設置樣式和寫數據,詳細使用就參考API吧。 http://poi.apache.org/apidocs/org/apache/poi/xssf/streaming/SXSSFWorkbook.html



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