POI&easyExcel

狂神整理

 

 

POI 和 easyExcel 講解

  1. 將用戶信息導出爲excel表格(導出數據....)
  2. 將Excel表中的信息錄入到網站數據庫(習題上傳....)

開發中經常會設計到excel的處理,如導出Excel,導入Excel到數據庫中!

操作Excel目前比較流行的就是 Apache POI 和 阿里巴巴的 easyExcel

Apache POI

  • Apache POI 官網:https://poi.apache.org/

easyExcel

  • easyExcel 官網地址:https://github.com/alibaba/easyexcel

EasyExcel 是阿里巴巴開源的一個excel處理框架,以使用簡單、節省內存著稱

EasyExcel 能大大減少佔用內存的主要原因是在解析 Excel 時沒有將文件數據一次性全部加載到內存中,而是從磁盤上一行行讀取數據,逐個解析。

官方文檔:https://www.yuque.com/easyexcel/doc/easyexcel

POI-Excel寫

  • 引入pom依賴

xml

<dependencies>
    <!--xls(03)-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.9</version>
    </dependency>

    <!--xlsx(07)-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.9</version>
    </dependency>
    
    <!--日期格式化工具-->
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.10.1</version>
    </dependency>

    <!--test-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>
  • 03 | 07 版本的寫,就是對象不同,方法一樣的!
  • 2003 版本和 2007 版本存在兼容性的問題!03最多隻有 65535 行!

03版本:

@Test
public void testWrite03() throws Exception {
    // 1、創建一個工作簿
    Workbook workbook = new HSSFWorkbook();
    // 2、創建一個工作表
    Sheet sheet = workbook.createSheet("狂神觀衆統計表");
    // 3、創建一個行  (1,1)
    Row row1 = sheet.createRow(0);
    // 4、創建一個單元格
    Cell cell11 = row1.createCell(0);
    cell11.setCellValue("今日新增觀衆");
    // (1,2)
    Cell cell12 = row1.createCell(1);
    cell12.setCellValue(666);

    // 第二行 (2,1)
    Row row2 = sheet.createRow(1);
    Cell cell21 = row2.createCell(0);
    cell21.setCellValue("統計時間");
    // (2,2)
    Cell cell22 = row2.createCell(1);
    String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
    cell22.setCellValue(time);

    // 生成一張表(IO 流)  03 版本就是使用 xls結尾!
    FileOutputStream fileOutputStream = new FileOutputStream(PATH + "狂神觀衆統計表03.xls");
    // 輸出
    workbook.write(fileOutputStream);
    // 關閉流
    fileOutputStream.close();

    System.out.println("狂神觀衆統計表03 生成完畢!");

}

07版本:

@Test
public void testWrite07() throws Exception {
    // 1、創建一個工作簿 07
    Workbook workbook = new XSSFWorkbook();
    // 2、創建一個工作表
    Sheet sheet = workbook.createSheet("狂神觀衆統計表");
    // 3、創建一個行  (1,1)
    Row row1 = sheet.createRow(0);
    // 4、創建一個單元格
    Cell cell11 = row1.createCell(0);
    cell11.setCellValue("今日新增觀衆");
    // (1,2)
    Cell cell12 = row1.createCell(1);
    cell12.setCellValue(666);

    // 第二行 (2,1)
    Row row2 = sheet.createRow(1);
    Cell cell21 = row2.createCell(0);
    cell21.setCellValue("統計時間");
    // (2,2)
    Cell cell22 = row2.createCell(1);
    String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
    cell22.setCellValue(time);

    // 生成一張表(IO 流)  03 版本就是使用 xlsx結尾!
    FileOutputStream fileOutputStream = new FileOutputStream(PATH + "狂神觀衆統計表07.xlsx");
    // 輸出
    workbook.write(fileOutputStream);
    // 關閉流
    fileOutputStream.close();

    System.out.println("狂神觀衆統計表03 生成完畢!");

}
  • 注意對象的一個區別,文件後綴!

 

數據批量導入

大文件寫HSSF

  • 缺點:最多隻能處理65536行,否則會拋出異常
java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)
  • 優點:過程中寫入緩存,不操作磁盤,最後一次性寫入磁盤,速度快

測試速度

@Test
public void testWrite03BigData() throws IOException {
    // 時間
    long begin = System.currentTimeMillis();

    // 創建一個薄
    Workbook workbook = new HSSFWorkbook();
    // 創建表
    Sheet sheet = workbook.createSheet();
    // 寫入數據
    for (int rowNum = 0; rowNum < 65537; rowNum++) {
        Row row = sheet.createRow(rowNum);
        for (int cellNum = 0; cellNum < 10 ; cellNum++) {
            Cell cell = row.createCell(cellNum);
            cell.setCellValue(cellNum);
        }
    }
    System.out.println("over");
    FileOutputStream outputStream = new FileOutputStream(PATH + "testWrite03BigData.xls");
    workbook.write(outputStream);
    outputStream.close();
    long end = System.currentTimeMillis();
    System.out.println((double) (end-begin)/1000);
}

大文件寫XSSF

  • 缺點:寫數據時速度非常慢,非常耗內存,也會發生內存溢出,如100萬條
  • 優點:可以寫較大的數據量,如20萬條

測試速度

@Test
public void testWrite07BigData() throws IOException {
    // 時間
    long begin = System.currentTimeMillis();

    // 創建一個薄
    Workbook workbook = new XSSFWorkbook();
    // 創建表
    Sheet sheet = workbook.createSheet();
    // 寫入數據
    for (int rowNum = 0; rowNum < 100000; rowNum++) {
        Row row = sheet.createRow(rowNum);
        for (int cellNum = 0; cellNum < 10 ; cellNum++) {
            Cell cell = row.createCell(cellNum);
            cell.setCellValue(cellNum);
        }
    }
    System.out.println("over");
    FileOutputStream outputStream = new FileOutputStream(PATH + "testWrite07BigData.xlsx");
    workbook.write(outputStream);
    outputStream.close();
    long end = System.currentTimeMillis();
    System.out.println((double) (end-begin)/1000);
}

大文件寫SXSSF

  • 優點:可以寫非常大的數據量,如100萬條甚至更多條,寫數據速度快,佔用更少的內存
  • 過程中會產生臨時文件,需要清理臨時文件
  • 默認由100條記錄被保存在內存中,如果超過這數量,則最前面的數據被寫入臨時文件
  • 如果想自定義內存中數據的數量,可以使用new SXSSFWorkbook ( 數量 )

測試速度

@Test
public void testWrite07BigDataS() throws IOException {
    // 時間
    long begin = System.currentTimeMillis();

    // 創建一個薄
    Workbook workbook = new SXSSFWorkbook();
    // 創建表
    Sheet sheet = workbook.createSheet();
    // 寫入數據
    for (int rowNum = 0; rowNum < 100000; rowNum++) {
        Row row = sheet.createRow(rowNum);
        for (int cellNum = 0; cellNum < 10 ; cellNum++) {
            Cell cell = row.createCell(cellNum);
            cell.setCellValue(cellNum);
        }
    }
    System.out.println("over");
    FileOutputStream outputStream = new FileOutputStream(PATH + "testWrite07BigDataS.xlsx");
    workbook.write(outputStream);
    outputStream.close();
    // 清除臨時文件!
    ((SXSSFWorkbook) workbook).dispose();
    long end = System.currentTimeMillis();
    System.out.println((double) (end-begin)/1000);
}
  • SXSSFWorkbook-來至官方的解釋:實現“BigGridDemo”策略的流式XSSFWorkbook版本。這允許寫入非常大的文件而不會耗盡內存,因爲任何時候只有可配置的行部分被保存在內存中。
  • 請注意,仍然可能會消耗大量內存,這些內存基於您正在使用的功能,例如合併區域,註釋......仍然只存儲在內存中,因此如果廣泛使用,可能需要大量內存。

POI-Excel讀

03版本

@Test
public void testRead03() throws Exception {

    // 獲取文件流
    FileInputStream inputStream = new FileInputStream(PATH + "kuang-poi狂神觀衆統計表03.xls");

    // 1、創建一個工作簿。 使用excel能操作的這邊他都可以操作!
    Workbook workbook = new HSSFWorkbook(inputStream);
    // 2、得到表
    Sheet sheet = workbook.getSheetAt(0);
    // 3、得到行
    Row row = sheet.getRow(0);
    // 4、得到列
    Cell cell = row.getCell(1);

    // 讀取值的時候,一定需要注意類型!
    // getStringCellValue 字符串類型
    //        System.out.println(cell.getStringCellValue());
    System.out.println(cell.getNumericCellValue());
    inputStream.close();
}

07版本

@Test
public void testRead07() throws Exception {

    // 獲取文件流
    FileInputStream inputStream = new FileInputStream(PATH + "kuang-poi狂神觀衆統計表07.xlsx");

    // 1、創建一個工作簿。 使用excel能操作的這邊他都可以操作!
    Workbook workbook = new XSSFWorkbook(inputStream);
    // 2、得到表
    Sheet sheet = workbook.getSheetAt(0);
    // 3、得到行
    Row row = sheet.getRow(0);
    // 4、得到列
    Cell cell = row.getCell(1);

    // 讀取值的時候,一定需要注意類型!
    // getStringCellValue 字符串類型
    //        System.out.println(cell.getStringCellValue());
    System.out.println(cell.getNumericCellValue());
    inputStream.close();
}

讀取不同的數據類型(最麻煩的就是這裏了!)

 

@Test
public void testCellType() throws Exception {
    // 獲取文件流
    FileInputStream inputStream = new FileInputStream(PATH + "明細表.xls");

    // 創建一個工作簿。 使用excel能操作的這邊他都可以操作!
    Workbook workbook = new HSSFWorkbook(inputStream);
    Sheet sheet = workbook.getSheetAt(0);
    // 獲取標題內容
    Row rowTitle = sheet.getRow(0);
    if (rowTitle!=null) {
        // 一定要掌握
        int cellCount = rowTitle.getPhysicalNumberOfCells();
        for (int cellNum = 0; cellNum < cellCount; cellNum++) {
            Cell cell = rowTitle.getCell(cellNum);
            if (cell!=null){
                int cellType = cell.getCellType();
                String cellValue = cell.getStringCellValue();
                System.out.print(cellValue + " | ");
            }
        }
        System.out.println();
    }

    // 獲取表中的內容
    int rowCount = sheet.getPhysicalNumberOfRows();
    for (int rowNum = 1; rowNum < rowCount ; rowNum++) {
        Row rowData = sheet.getRow(rowNum);
        if (rowData!=null){
            // 讀取列
            int cellCount = rowTitle.getPhysicalNumberOfCells();
            for (int cellNum = 0; cellNum < cellCount ; cellNum++) {
                System.out.print("[" +(rowNum+1) + "-" + (cellNum+1) + "]");

                Cell cell = rowData.getCell(cellNum);
                // 匹配列的數據類型
                if (cell!=null) {
                    int cellType = cell.getCellType();
                    String cellValue = "";

                    switch (cellType) {
                        case HSSFCell.CELL_TYPE_STRING: // 字符串
                            System.out.print("【String】");
                            cellValue = cell.getStringCellValue();
                            break;
                        case HSSFCell.CELL_TYPE_BOOLEAN: // 布爾
                            System.out.print("【BOOLEAN】");
                            cellValue = String.valueOf(cell.getBooleanCellValue());
                            break;
                        case HSSFCell.CELL_TYPE_BLANK: // 空
                            System.out.print("【BLANK】");
                            break;
                        case HSSFCell.CELL_TYPE_NUMERIC: // 數字(日期、普通數字)
                            System.out.print("【NUMERIC】");
                            if (HSSFDateUtil.isCellDateFormatted(cell)){ // 日期
                                System.out.print("【日期】");
                                Date date = cell.getDateCellValue();
                                cellValue = new DateTime(date).toString("yyyy-MM-dd");
                            }else {
                                // 不是日期格式,防止數字過長!
                                System.out.print("【轉換爲字符串輸出】");
                                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                                cellValue = cell.toString();
                            }
                            break;
                        case HSSFCell.CELL_TYPE_ERROR:
                            System.out.print("【數據類型錯誤】");
                            break;
                    }
                    System.out.println(cellValue);
                }
            }
        }
    }
    inputStream.close();
}
  • 注意類型轉換問題

計算公式 (瞭解即可!)

@Test
public void testFormula() throws Exception {
    FileInputStream inputStream = new FileInputStream(PATH + "公式.xls");
    Workbook workbook = new HSSFWorkbook(inputStream);
    Sheet sheet = workbook.getSheetAt(0);

    Row row = sheet.getRow(4);
    Cell cell = row.getCell(0);

    // 拿到計算公司 eval
    FormulaEvaluator FormulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook)workbook);

    // 輸出單元格的內容
    int cellType = cell.getCellType();
    switch (cellType){
        case Cell.CELL_TYPE_FORMULA: // 公式
            String formula = cell.getCellFormula();
            System.out.println(formula);

            // 計算
            CellValue evaluate = FormulaEvaluator.evaluate(cell);
            String cellValue = evaluate.formatAsString();
            System.out.println(cellValue);
            break;
    }

}

 

EasyExcel操作

導入依賴

xml

<dependencies>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.0-beta2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

        <!--日期格式化工具-->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>

        <!--test-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

寫入測試

  • https://www.yuque.com/easyexcel/doc/read

讀取測試

  • https://www.yuque.com/easyexcel/doc/read

固定套路:

  1. 寫入,固定類格式進行寫入
  2. 讀取,根據監聽器設置的規則進行讀取!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章