首先大數據量的下載,通常的Excel下載操做是不可能完成的,會致使內存溢出緩存
SXSSFWorkbook 是專門用於大數據了的導出 app
這個參數,會指定一個sheet可讀取的row數目,超過該數目的row,會被寫入到磁盤文件中,進而不能在經過getRow訪問到,經過這種方式,內存使用空間就縮小不少了。 須要注意的是,若是該值指定爲-1,說明不限制行數,全部記錄都寫入內存中;該值不能取0,由於這意味着任何新row都會寫入磁盤,進而不能訪問,可是新row還沒來得及createCellxss
當寫sheet的時候,臨時文件可能遠比結果文件要大,因此提供了壓縮臨時文件的接口,經過壓縮,磁盤上的xml的臨時文件將會被打包,進而下降磁盤佔用空間。ide
先上代碼再說函數
1 /** 2 * Excel通用下載方法 3 * @param request 4 * @param response 5 * @param fileName 6 * 文件名 7 * @param titleNameList 8 * 標題頭部 9 * @param cellNameList 10 * 行字段的name,主要用於map的get(),無則爲null 11 * @param dataList 12 * 內容 支持類型 對象 map集合 13 */ 14 public static <E> void downLoad(HttpServletRequest request, HttpServletResponse response, String fileName, 15 List<String> titleNameList,List<String> cellNameList, List<E> dataList) { 16 OutputStream os = null; 17 try { 18 response.setContentType("application/force-download"); // 設置下載類型 19 20 response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // 設置文件的名稱 21 os = response.getOutputStream(); // 輸出流 22 SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 內存中保留 1000 條數據,以避免內存溢出,其他寫入 硬盤 23 // 得到該工做區的第一個sheet 24 Sheet sheet1 = wb.createSheet("sheet1"); 25 String mapstring=null; 26 int excelRow = 0; 27 List<String> fieldNameList = new ArrayList<>(); 28 // 標題行 29 Row titleRow = (Row) sheet1.createRow(excelRow++); 30 int titleSize = titleNameList.size(); 31 for (int i = 0; i < titleSize; i++) { 32 Cell cell = titleRow.createCell(i); 33 cell.setCellValue(titleNameList.get(i)); 34 } 35 int dataSize = dataList.size(); 36 for (int i = 0; i < dataSize; i++) { 37 // 明細行 38 Row contentRow = (Row) sheet1.createRow(excelRow++); 39 Object object = dataList.get(i); 40 if (object instanceof Map) { 41 Map<String, Object> objectMap = (Map<String, Object>) object; 42 for (int j = 0; j < titleSize; j++) { 43 mapstring=objectMap.get(cellNameList.get(j))+""; 44 Cell cell = contentRow.createCell(j); 45 if (!"".equals(mapstring)&&mapstring!=null&&!"null".equals(mapstring)) { 46 cell.setCellValue(mapstring); 47 }else { 48 cell.setCellValue(""); 49 } 50 } 51 } else { 52 53 if (i == 0) { 54 if (cellNameList!=null&&cellNameList.size()>0) { 55 fieldNameList.addAll(cellNameList); 56 }else { 57 Field[] fields = object.getClass().getDeclaredFields(); 58 for (Field field : fields) { 59 field.setAccessible(true); 60 fieldNameList.add(field.getName()); 61 } 62 } 63 } 64 for (int j = 0; j < titleSize; j++) { 65 Cell cell = contentRow.createCell(j); 66 Field field = object.getClass().getDeclaredField(fieldNameList.get(j)); 67 field.setAccessible(true); 68 Object fieldObj=field.get(object) ; 69 if (fieldObj != null&&!"null".equals(fieldObj)) { 70 cell.setCellValue(fieldObj.toString()); 71 } else { 72 cell.setCellValue(""); 73 } 74 75 } 76 77 78 } 79 } 80 wb.write(os); 81 } catch (Exception e) { 82 e.printStackTrace(); 83 } finally { 84 try { 85 if (os != null) { 86 os.close(); 87 } 88 } catch (IOException e) { 89 e.printStackTrace(); 90 } // 關閉輸出流 91 } 92 93 }
讀取大數據的Excel文件大數據
直接上代碼 ui
public class SheetHandler extends DefaultHandler { /** * 單元格中的數據可能的數據類型 */ enum CellDataType { BOOL, ERROR, FORMULA, INLINESTR, SSTINDEX, NUMBER, DATE, NULL } /** * 共享字符串表 */ private SharedStringsTable sst; /** * 上一次的索引值 */ private String lastIndex; /** * 文件的絕對路徑 */ private String filePath = ""; /** * 工做表索引 */ private int sheetIndex = 0; /** * sheet名 */ private String sheetName = ""; /** * 總行數 */ private int totalRows=0; /** * 一行內cell集合 */ private List<String> cellList = new ArrayList<String>(); /** * 判斷整行是否爲空行的標記 */ private boolean flag = false; /** * 當前行 */ private int curRow = 1; /** * 當前列 */ private int curCol = 0; /** * T元素標識 */ private boolean isTElement; /** * 異常信息,若是爲空則表示沒有異常 */ private String exceptionMessage; /** * 單元格數據類型,默認爲字符串類型 */ private CellDataType nextDataType = CellDataType.SSTINDEX; private final DataFormatter formatter = new DataFormatter(); /** * 單元格日期格式的索引 */ private short formatIndex; /** * 日期格式字符串 */ private String formatString; //定義前一個元素和當前元素的位置,用來計算其中空的單元格數量,如A6和A8等 private String preRef = null, ref = null; //定義該文檔一行最大的單元格數,用來補全一行最後可能缺失的單元格 private String maxRef = null; private int maxCol=0; private int nowcol; /** * 單元格 */ private StylesTable stylesTable; /** * 日期格式化 yyyy-MM-dd */ private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); /** * 日期格式化 */ private SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 如今的時間 */ private String dateTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); /** * 一個表格的全部數據 */ private List<List<String>> sheetList=new ArrayList<>(); /** * 操做人員 */ private String userName; private static int startElements=0; private static int endElement=0; /* public static void main(String[] args) { SheetHandler sheetHandler=new SheetHandler(); File file=new File("C:\\Users\\Administrator\\Desktop\\jichu.xlsx"); try { sheetHandler.process(new FileInputStream(file), "周光林"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ /** * 遍歷工做簿中全部的電子表格 * 並緩存在mySheetList中 * * @param filename * @throws Exception */ public List<List<String>> process(InputStream in,String userName) throws Exception { this.userName=userName; OPCPackage pkg = OPCPackage.open(in); XSSFReader xssfReader = new XSSFReader(pkg); stylesTable = xssfReader.getStylesTable(); SharedStringsTable sst = xssfReader.getSharedStringsTable(); XMLReader parser = XMLReaderFactory.createXMLReader(); this.sst = sst; parser.setContentHandler(this); XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); while (sheets.hasNext()) { //遍歷sheet curRow = 1; //標記初始行爲第一行 sheetIndex++; InputStream sheet = sheets.next(); //sheets.next()和sheets.getSheetName()不能換位置,不然sheetName報錯 sheetName = sheets.getSheetName(); // System.err.println(new BufferedReader(new InputStreamReader(sheet)).readLine()); InputSource sheetSource = new InputSource(sheet); parser.parse(sheetSource); //解析excel的每條記錄,在這個過程當中startElement()、characters()、endElement()這三個函數會依次執行 sheet.close(); } if (in!=null) { in.close(); } return sheetList; //返回該excel文件的總行數,不包括首列和空行 } /** * 第一個執行 * * @param uri * @param localName * @param name * @param attributes * @throws SAXException */ @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { //c => 單元格 if ("c".equals(name)) { //當前單元格的位置 ref = attributes.getValue("r"); //設定單元格類型 this.setNextDataType(attributes); } //當元素爲t時 if ("t".equals(name)) { isTElement = true; } else { isTElement = false; } //置空 lastIndex = ""; } /** * 第二個執行 * 獲得單元格對應的索引值或是內容值 * 若是單元格類型是字符串、INLINESTR、數字、日期,lastIndex則是索引值 * 若是單元格類型是布爾值、錯誤、公式,lastIndex則是內容值 * @param ch * @param start * @param length * @throws SAXException */ @Override public void characters(char[] ch, int start, int length) throws SAXException { lastIndex += new String(ch, start, length); } /** * 第三個執行 * * @param uri * @param localName * @param name * @throws SAXException */ @Override public void endElement(String uri, String localName, String name) throws SAXException { //t元素也包含字符串 if (isTElement) {//這個程序沒通過 //將單元格內容加入rowlist中,在這以前先去掉字符串先後的空白符 String value = lastIndex.trim(); cellList.add(curCol, value); curCol++; isTElement = false; //若是裏面某個單元格含有值,則標識該行不爲空行 if (value != null && !"".equals(value)) { flag = true; } } else if ("v".equals(name)) { //v => 單元格的值,若是單元格是字符串,則v標籤的值爲該字符串在SST中的索引 String value = this.getDataValue(lastIndex.trim(), "");//根據索引值獲取對應的單元格值 //補全單元格之間的空單元格 if (preRef!=null) { if (!ref.equals(preRef)) { int len = countNullCell(ref, preRef); for (int i = 0; i < len; i++) { cellList.add(curCol, ""); curCol++; } } } preRef=ref; cellList.add(curCol, value); curCol++; //若是裏面某個單元格含有值,則標識該行不爲空行 if (value != null && !"".equals(value)) { flag = true; } } else { //若是標籤名稱爲row,這說明已到行尾,調用optRows()方法 if ("row".equals(name)) { //默認第一行爲表頭,以該行單元格數目爲最大數目 if (curRow == 1) { maxRef = ref; maxCol=curCol; } //補全一行尾部可能缺失的單元格 if (maxRef != null) { int len = countNullCell(maxRef, ref); for (int i = 0; i <= len; i++) { cellList.add(curCol, ""); curCol++; } } if (flag&&curRow!=1){ //該行不爲空行且該行不是第一行,則發送(第一行爲列名,不須要) nowcol=cellList.size(); if (cellList.size()<maxCol) { for (int i = 0; i <maxCol-nowcol; i++) { cellList.add(""); } } if (nowcol>maxCol) { for (int i = nowcol-1; i >maxCol-1; i--) { cellList.remove(i); } } cellList.add(userName); cellList.add(dateTime); sheetList.add(new ArrayList<>(cellList)); totalRows++; } cellList.clear(); curRow++; curCol = 0; preRef = null; ref = null; flag=false; } } } /** * 處理數據類型 * * @param attributes */ public void setNextDataType(Attributes attributes) { nextDataType = CellDataType.NUMBER; //cellType爲空,則表示該單元格類型爲數字 formatIndex = -1; formatString = null; String cellType = attributes.getValue("t"); //單元格類型 String cellStyleStr = attributes.getValue("s"); // String columnData = attributes.getValue("r"); //獲取單元格的位置,如A1,B1 if ("b".equals(cellType)) { //處理布爾值 nextDataType = CellDataType.BOOL; } else if ("e".equals(cellType)) { //處理錯誤 nextDataType = CellDataType.ERROR; } else if ("inlineStr".equals(cellType)) { nextDataType = CellDataType.INLINESTR; } else if ("s".equals(cellType)) { //處理字符串 nextDataType = CellDataType.SSTINDEX; } else if ("str".equals(cellType)) { nextDataType = CellDataType.FORMULA; } if (cellStyleStr != null) { //處理日期 int styleIndex = Integer.parseInt(cellStyleStr); XSSFCellStyle style = stylesTable.getStyleAt(styleIndex); formatIndex = style.getDataFormat(); formatString = style.getDataFormatString(); if (formatString == null) { nextDataType = CellDataType.NULL; formatString = BuiltinFormats.getBuiltinFormat(formatIndex); }else if (formatString.contains("m/d/yy") || formatString.contains("yyyy/mm/dd")|| formatString.contains("yyyy/m/d")) { nextDataType = CellDataType.DATE; formatString = "yyyy-MM-dd"; } } } /** * 對解析出來的數據進行類型處理 * @param value 單元格的值, * value表明解析:BOOL的爲0或1, ERROR的爲內容值,FORMULA的爲內容值,INLINESTR的爲索引值需轉換爲內容值, * SSTINDEX的爲索引值需轉換爲內容值, NUMBER爲內容值,DATE爲內容值 * @param thisStr 一個空字符串 * @return */ @SuppressWarnings("deprecation") public String getDataValue(String value, String thisStr) { switch (nextDataType) { // 這幾個的順序不能隨便交換,交換了極可能會致使數據錯誤 case BOOL: //布爾值 char first = value.charAt(0); thisStr = first == '0' ? "FALSE" : "TRUE"; break; case ERROR: //錯誤 thisStr = value.toString(); break; case FORMULA: //公式 thisStr = '"' + value.toString() + '"'; break; case INLINESTR: XSSFRichTextString rtsi = new XSSFRichTextString(value.toString()); thisStr = rtsi.toString(); rtsi = null; break; case SSTINDEX: //字符串 String sstIndex = value.toString(); try { int idx = Integer.parseInt(sstIndex); XSSFRichTextString rtss = new XSSFRichTextString(sst.getEntryAt(idx));//根據idx索引值獲取內容值 thisStr = rtss.toString(); rtss = null; } catch (NumberFormatException ex) { thisStr = value.toString(); } break; case NUMBER: //數字 if (formatString != null) { thisStr = formatter.formatRawCellContents(Double.parseDouble(value), formatIndex, formatString).trim(); } else { thisStr = value; } thisStr = thisStr.replace("_", "").trim(); break; case DATE: //日期 try { thisStr = formatter.formatRawCellContents(Double.parseDouble(value), formatIndex, formatString); }catch (Exception e) { thisStr="0000-00-00"; } // 對日期字符串做特殊處理,去掉T thisStr = thisStr.replace("T", " "); break; default: if (Integer.parseInt(value)>20000) { Date date = DateUtil.getJavaDate(Double.parseDouble(value)); thisStr =sdf.format(date); }else { thisStr="11111"; } break; } return thisStr; } public int countNullCell(String ref, String preRef) { //excel2007最大行數是1048576,最大列數是16384,最後一列列名是XFD String xfd = ref.replaceAll("\\d+", ""); String xfd_1 = preRef.replaceAll("\\d+", ""); xfd = fillChar(xfd, 3, '@', true); xfd_1 = fillChar(xfd_1, 3, '@', true); char[] letter = xfd.toCharArray(); char[] letter_1 = xfd_1.toCharArray(); int res = (letter[0] - letter_1[0]) * 26 * 26 + (letter[1] - letter_1[1]) * 26 + (letter[2] - letter_1[2]); return res - 1; } public String fillChar(String str, int len, char let, boolean isPre) { int len_1 = str.length(); if (len_1 < len) { if (isPre) { for (int i = 0; i < (len - len_1); i++) { str = let + str; } } else { for (int i = 0; i < (len - len_1); i++) { str = str + let; } } } return str; } /** * @return the exceptionMessage */ public String getExceptionMessage() { return exceptionMessage; } }
SheetHandler sheetHandler=new SheetHandler(); List<List<String>> lists=sheetHandler.process(in,userName);