1. 程式人生 > >Excel---匯出與讀取(大資料量)

Excel---匯出與讀取(大資料量)

Excel下載

  首先大資料量的下載,一般的Excel下載操作是不可能完成的,會導致記憶體溢位

  SXSSFWorkbook 是專門用於大資料了的匯出  

  構造入參rowAccessWindowSize

  這個引數,會指定一個sheet可讀取的row數目,超過該數目的row,會被寫入到磁碟檔案中,進而不能在通過getRow訪問到,通過這種方式,記憶體使用空間就縮小很多了。 需要注意的是,如果該值指定為-1,說明不限制行數,所有記錄都寫入記憶體中;該值不能取0,因為這意味著任何新row都會寫入磁碟,進而不能訪問,但是新row還沒來得及createCell

  setCompressTempFiles方法

  當寫sheet的時候,臨時檔案可能遠比結果檔案要大,所以提供了壓縮臨時檔案的介面,通過壓縮,磁碟上的xml的臨時檔案將會被打包,進而降低磁碟佔用空間。

 先上程式碼再說

 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檔案

直接上程式碼 

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);