解决大批量数据导出Excel产生内存溢出的方案

  1. 上面的代码也不支持sheet,下面的就可以了:
  2. @SuppressWarnings("unchecked")   
  3. public class XlsMergeUtil {   
  4.   private static Logger logger = LoggerFactory.getLogger(XlsMergeUtil.class);   
  5.   
  6.   /**  
  7.    * 将多个Xls文件合并为一个,适用于只有一个sheet,并且格式相同的文档  
  8.    * @param inputs 输入的Xls文件,第一个XLS文件必须给出足够sheet空间  
  9.    * 例如,总共200000行数据,第一个文件至少3个空白sheet  
  10.    * @param out 输出文件  
  11.    */  
  12.   public static void merge(InputStream[] inputs, OutputStream out) {   
  13.     if (inputs == null || inputs.length <= 1) {   
  14.       throw new IllegalArgumentException("没有传入输入流数组,或只有一个输入流.");   
  15.     }   
  16.   
  17.     List<Record> rootRecords = getRecords(inputs[0]);   
  18.     Workbook workbook = Workbook.createWorkbook(rootRecords);   
  19.     List<Sheet> sheets = getSheets(workbook, rootRecords);   
  20.     if(sheets == null || sheets.size() == 0) {   
  21.       throw new IllegalArgumentException("第一篇文档的格式错误,必须有至少一个sheet");   
  22.     }   
  23.     //以第一篇文档的第一个sheet为根,以后的数据都追加在这个sheet后面   
  24.     Sheet rootSheet = sheets.get(0);    
  25.     int rootRows = getRowsOfSheet(rootSheet); //记录第一篇文档的行数,以后的行数在此基础上增加   
  26.     rootSheet.setLoc(rootSheet.getDimsLoc());   
  27.     Map<Integer, Integer> map = new HashMap(10000);   
  28.     int sheetIndex = 0;   
  29.        
  30.     for (int i = 1; i < inputs.length; i++) { //从第二篇开始遍历   
  31.       List<Record> records = getRecords(inputs[i]);   
  32.       //达到最大行数限制,换一个sheet   
  33.       if(getRows(records) + rootRows >= RowRecord.MAX_ROW_NUMBER) {   
  34.         if((++sheetIndex) > (sheets.size() - 1)) {   
  35.           logger.warn("第一个文档给出的sheets小于需要的数量,部分数据未能合并.");   
  36.           break;   
  37.         }   
  38.         rootSheet = sheets.get(sheetIndex);   
  39.         rootRows = getRowsOfSheet(rootSheet);   
  40.         rootSheet.setLoc(rootSheet.getDimsLoc());   
  41.         logger.debug("切换Sheet{}", sheetIndex);   
  42.       }   
  43.       int rowsOfCurXls = 0;   
  44.       //遍历当前文档的每一个record   
  45.       for (Iterator itr = records.iterator(); itr.hasNext();) {   
  46.         Record record = (Record) itr.next();   
  47.         if (record.getSid() == RowRecord.sid) { //如果是RowRecord   
  48.           RowRecord rowRecord = (RowRecord) record;   
  49.           //调整行号   
  50.           rowRecord.setRowNumber(rootRows + rowRecord.getRowNumber());   
  51.           rootSheet.addRow(rowRecord); //追加Row   
  52.           rowsOfCurXls++; //记录当前文档的行数   
  53.         }   
  54.         //SST记录,SST保存xls文件中唯一的String,各个String都是对应着SST记录的索引   
  55.         else if (record.getSid() == SSTRecord.sid) {   
  56.           SSTRecord sstRecord = (SSTRecord) record;   
  57.           for (int j = 0; j < sstRecord.getNumUniqueStrings(); j++) {   
  58.             int index = workbook.addSSTString(sstRecord.getString(j));   
  59.             //记录原来的索引和现在的索引的对应关系   
  60.             map.put(Integer.valueOf(j), Integer.valueOf(index));   
  61.           }   
  62.         } else if (record.getSid() == LabelSSTRecord.sid) {   
  63.           LabelSSTRecord label = (LabelSSTRecord) record;   
  64.           //调整SST索引的对应关系   
  65.           label.setSSTIndex(map.get(Integer.valueOf(label.getSSTIndex())));   
  66.         }   
  67.         //追加ValueCell   
  68.         if (record instanceof CellValueRecordInterface) {   
  69.           CellValueRecordInterface cell = (CellValueRecordInterface) record;   
  70.           int cellRow = cell.getRow() + rootRows;   
  71.           cell.setRow(cellRow);   
  72.           rootSheet.addValueRecord(cellRow, cell);   
  73.         }   
  74.       }   
  75.       rootRows += rowsOfCurXls;   
  76.     }   
  77.        
  78.     byte[] data = getBytes(workbook, sheets.toArray(new Sheet[0]));   
  79.     write(out, data);   
  80.   }   
  81.   
  82.   static void write(OutputStream out, byte[] data) {   
  83.     POIFSFileSystem fs = new POIFSFileSystem();   
  84.     // Write out the Workbook stream   
  85.     try {   
  86.       fs.createDocument(new ByteArrayInputStream(data), "Workbook");   
  87.       fs.writeFilesystem(out);   
  88.       out.flush();   
  89.     } catch (IOException e) {   
  90.       e.printStackTrace();   
  91.     } finally {   
  92.       try {   
  93.         out.close();   
  94.       } catch (IOException e) {   
  95.         e.printStackTrace();   
  96.       }   
  97.     }   
  98.   }   
  99.   
  100.   static List<Sheet> getSheets(Workbook workbook, List records) {   
  101.     int recOffset = workbook.getNumRecords();   
  102.     int sheetNum = 0;   
  103.   
  104.     // convert all LabelRecord records to LabelSSTRecord   
  105.     convertLabelRecords(records, recOffset, workbook);   
  106.     List<Sheet> sheets = new ArrayList();   
  107.     while (recOffset < records.size()) {   
  108.       Sheet sh = Sheet.createSheet(records, sheetNum++, recOffset);   
  109.   
  110.       recOffset = sh.getEofLoc() + 1;   
  111.       if (recOffset == 1) {   
  112.         break;   
  113.       }   
  114.       sheets.add(sh);   
  115.     }   
  116.     return sheets;   
  117.   }   
  118.   
  119.   static int getRows(List<Record> records) {   
  120.     int row = 0;   
  121.     for (Iterator itr = records.iterator(); itr.hasNext();) {   
  122.       Record record = (Record) itr.next();   
  123.       if (record.getSid() == RowRecord.sid) {   
  124.         row++;   
  125.       }   
  126.     }   
  127.     return row;   
  128.   }   
  129.      
  130.   static int getRowsOfSheet(Sheet sheet) {   
  131.     int rows = 0;   
  132.     sheet.setLoc(0);   
  133.     while(sheet.getNextRow() != null) {   
  134.       rows++;   
  135.     }   
  136.     return rows;   
  137.   }   
  138.   
  139.   @SuppressWarnings("deprecation")   
  140.   static List<Record> getRecords(InputStream input) {   
  141.     try {   
  142.       POIFSFileSystem poifs = new POIFSFileSystem(input);   
  143.       InputStream stream = poifs.getRoot().createDocumentInputStream("Workbook");   
  144.       return org.apache.poi.hssf.record.RecordFactory.createRecords(stream);   
  145.     } catch (IOException e) {   
  146.       logger.error("IO异常:{}", e.getMessage());   
  147.       e.printStackTrace();   
  148.     }   
  149.     return Collections.EMPTY_LIST;   
  150.   }   
  151.   
  152.   static void convertLabelRecords(List records, int offset, Workbook workbook) {   
  153.   
  154.     for (int k = offset; k < records.size(); k++) {   
  155.       Record rec = (Record) records.get(k);   
  156.   
  157.       if (rec.getSid() == LabelRecord.sid) {   
  158.         LabelRecord oldrec = (LabelRecord) rec;   
  159.   
  160.         records.remove(k);   
  161.         LabelSSTRecord newrec = new LabelSSTRecord();   
  162.         int stringid = workbook.addSSTString(new UnicodeString(oldrec.getValue()));   
  163.   
  164.         newrec.setRow(oldrec.getRow());   
  165.         newrec.setColumn(oldrec.getColumn());   
  166.         newrec.setXFIndex(oldrec.getXFIndex());   
  167.         newrec.setSSTIndex(stringid);   
  168.         records.add(k, newrec);   
  169.       }   
  170.     }   
  171.   }   
  172.   
  173.   public static byte[] getBytes(Workbook workbook, Sheet[] sheets) {   
  174.     // HSSFSheet[] sheets = getSheets();   
  175.     int nSheets = sheets.length;   
  176.   
  177.     // before getting the workbook size we must tell the sheets that   
  178.     // serialization is about to occur.   
  179.     for (int i = 0; i < nSheets; i++) {   
  180.       sheets[i].preSerialize();   
  181.     }   
  182.   
  183.     int totalsize = workbook.getSize();   
  184.     // pre-calculate all the sheet sizes and set BOF indexes   
  185.     int[] estimatedSheetSizes = new int[nSheets];   
  186.     for (int k = 0; k < nSheets; k++) {   
  187.       workbook.setSheetBof(k, totalsize);   
  188.       int sheetSize = sheets[k].getSize();   
  189.       estimatedSheetSizes[k] = sheetSize;   
  190.       totalsize += sheetSize;   
  191.     }   
  192.     logger.debug("分配内存{}bytes", totalsize);   
  193.     byte[] retval = new byte[totalsize];   
  194.     int pos = workbook.serialize(0, retval);   
  195.   
  196.     for (int k = 0; k < nSheets; k++) {   
  197.       int serializedSize = sheets[k].serialize(pos, retval);   
  198.       if (serializedSize != estimatedSheetSizes[k]) {   
  199.         // Wrong offset values have been passed in the call to setSheetBof() above.   
  200.         // For books with more than one sheet, this discrepancy would cause excel   
  201.         // to report errors and loose data while reading the workbook   
  202.         throw new IllegalStateException("Actual serialized sheet size (" + serializedSize   
  203.             + ") differs from pre-calculated size (" + estimatedSheetSizes[k] + ") for sheet (" + k   
  204.             + ")");   
  205.         // TODO - add similar sanity check to ensure that Sheet.serializeIndexRecord() does not   
  206.         // write mis-aligned offsets either   
  207.       }   
  208.       pos += serializedSize;   
  209.     }   
  210.     return retval;   
  211.   }   
  212.   
  213.   public static void main(String[] args) throws Exception {   
  214.     final String PATH = "E:\\projects\\java\\ws_0\\export\\data\\";   
  215.     InputStream[] inputs = new InputStream[25];   
  216.     inputs[0] = new java.io.FileInputStream(PATH + "07_10.xls");   
  217.     for(int i = 1; i < 25 ; i++) {   
  218.       inputs[i] = new java.io.FileInputStream(PATH + "07_01.xls");   
  219.     }   
  220.     OutputStream out = new FileOutputStream(PATH + "xx.xls");   
  221.     long t1 = System.currentTimeMillis();   
  222.     merge(inputs, out);   
  223.     System.out.println(System.currentTimeMillis() - t1);   
  224.   }   
  225.   
  226. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值