POI和EasyExcel 的使用筆記


文章首發於我的個人博客,歡迎訪問:https://blog.itzhouq.cn/poi
代碼地址:https://github.com/itzhouq/POIAndEasyExcelDemo

POI和EasyExcel 的使用筆記

我們經常需要將項目中的表格數據或者文檔數據進行導入或者導出操作,這個如果自己從零開始做還比較麻煩。比如我之前就職的公司都是自己做的組件,但是很不好用,BUG 太多。關於表格導入導出,市面上比較知名的開源就是 Apache 的POI 和 阿里巴巴的 EasyExcel了。EasyExcel 也是對 POI 的改進和封裝, 更加好用。下面通過一些 demo 學習如何使用這兩個開源組件。這兩個組件都不難,多看文檔就能會,尤其是 EasyExcel 的文檔非常詳細。這篇博客主要自己在寫 demo 的時候整理的筆記,方便以后使用的時候查閱。如果能幫到你那就更好了。

常用信息

1、將用戶的信息導出為 excel 表格。

2、將 Excel 表中的信息錄入到網站數據庫。

開發中經常會涉及到 excel 的 處理,如導出 Excel ,導入 Excel 到數據庫中。

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

Apache POI

Apache POI 官網: http://poi.apache.org/index.html

百度百科的解釋: Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。

結構:

HSSF - 提供讀寫[Microsoft Excel](https://baike.baidu.com/item/Microsoft Excel)格式檔案的功能。excel 2003 版本

XSSF - 提供讀寫Microsoft Excel OOXML格式檔案的功能。excel 207 版本

HWPF - 提供讀寫[Microsoft Word](https://baike.baidu.com/item/Microsoft Word)格式檔案的功能。

HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。

HDGF - 提供讀寫[Microsoft Visio](https://baike.baidu.com/item/Microsoft Visio)格式檔案的功能。

EasyExcel

GitHub 地址: https://github.com/alibaba/easyexcel

EasyExcel 官網: https://www.yuque.com/easyexcel/doc/easyexcel

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

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

下面是 EasyExcel 和 POI 在解析Excel 時的對比圖。


1、POI-Excel 寫

創建項目

1、建立一個空項目,創建普通的 Module 。

2、引入依賴:

<dependencies>
        <!-- xls03 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <!-- xlsx07 -->
        <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 版本:

package cn.itzhouq;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.joda.time.DateTime;
import org.junit.Test;

import java.io.FileOutputStream;

public class ExcelWriteTest {
    String PATH = "F:\\workspaces\\workspaces_idea\\POIAndEasyExcel\\itzhouq-poi";

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

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

        // 生成一張表  03版本的就是使用 xls 結尾
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "/人員統計表03.xls");
        workbook.write(fileOutputStream);
        // 關閉流
        fileOutputStream.close();
        System.out.println("人員統計表03.xls 生成完畢");
    }
}

大文件寫 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 < 65535; 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 fileOutputStream = new FileOutputStream(PATH + "/testWrite03BigData.xls");
    workbook.write(fileOutputStream);
    fileOutputStream.close();
    long end = System.currentTimeMillis();
    System.out.println((double) (end - begin) / 1000); // 1.295
}

大文件寫 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 < 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 fileOutputStream = new FileOutputStream(PATH + "/testWrite07BigData.xlsx");
    workbook.write(fileOutputStream);
    fileOutputStream.close();
    long end = System.currentTimeMillis();
    System.out.println((double) (end - begin) / 1000); // 7.39
}

大文件寫 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 < 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 fileOutputStream = new FileOutputStream(PATH + "/testWrite07BigDataS.xlsx");
    workbook.write(fileOutputStream);
    fileOutputStream.close();
    // 清除臨時文件
    ((SXSSFWorkbook) workbook).dispose();
    long end = System.currentTimeMillis();
    System.out.println((double) (end - begin) / 1000); // 1.859
}

SXSSFWorkbook 來自官方的解釋:實現“BigGridDemo” 策略的流式 SXSSFWorkbook 版本。這允許寫入非常大的文件而不會耗盡內存,因為任何時候只有可配置的行部分被保存在內存中。

請注意,仍然可能會消耗大量內存,這些內存基於你正在使用的功能,例如合並區域,注釋。。。仍然只存儲在內存中,因此如果廣泛使用,可能需要大量內存。


2、POI-Excel 讀

03 | 07 版本的讀操作

03 版本

String PATH = "F:\\workspaces\\workspaces_idea\\POIAndEasyExcel\\itzhouq-poi";

@Test
public void testRead03() throws IOException {
    // 獲取文件流
    FileInputStream fileInputStream = new FileInputStream(PATH + "/人員統計表03.xls");
    // 1. 創建一個工作簿,使用excel能操作的,代碼都能操作
    Workbook workbook = new HSSFWorkbook(fileInputStream);
    // 2. 得到表
    Sheet sheet = workbook.getSheetAt(0);
    // 3. 得到行
    Row row = sheet.getRow(0);
    // 4. 得到列
    Cell cell = row.getCell(0);
    System.out.println(cell.getStringCellValue()); // 今日新增人員
    Cell cell1 = row.getCell(1);
    System.out.println(cell1.getNumericCellValue()); // 666.0
    fileInputStream.close();
}

07 版本

@Test
public void testRead07() throws IOException {
    // 獲取文件流
    FileInputStream fileInputStream = new FileInputStream(PATH + "/人員統計表07.xlsx");
    // 1. 創建一個工作簿,使用excel能操作的,代碼都能操作
    Workbook workbook = new XSSFWorkbook(fileInputStream);
    // 2. 得到表
    Sheet sheet = workbook.getSheetAt(0);
    // 3. 得到行
    Row row = sheet.getRow(0);
    // 4. 得到列
    Cell cell = row.getCell(0);
    System.out.println(cell.getStringCellValue()); // 今日新增人員
    Cell cell1 = row.getCell(1);
    System.out.println(cell1.getNumericCellValue()); // 666.0
    fileInputStream.close();
}

注意獲取值的類型。

讀取不同的數據類型(最麻煩的點)

@Test
public void testCellType() throws IOException {
    // 獲取文件流
    FileInputStream fileInputStream = new FileInputStream(PATH + "/明細表.xls");
    // 創建一個工作簿
    Workbook workbook = new HSSFWorkbook(fileInputStream);
    Sheet sheet = workbook.getSheetAt(0);
    // 獲取標題內容
    Row rowTitle = sheet.getRow(0);
    if (rowTitle != null) {
        // 重點
        int rowCount = rowTitle.getPhysicalNumberOfCells(); // 獲取列的數量
        for (int cellNum = 0; cellNum < rowCount; 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("【UMERIC】");
                            if (HSSFDateUtil.isCellDateFormatted(cell)) { // 日期
                                System.out.print("【日期】");
                                Date date = cell.getDateCellValue();
                                cellValue = new DateTime(date).toString();
                            } 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);
                }
            }
        }
    }
    fileInputStream.close();
}

結果:

注意類型轉換問題。可以將上面的方法提取成工具類。

計算公式(了解)

import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 計算公式
 */
public class Formula {
    String PATH = "F:\\workspaces\\workspaces_idea\\POIAndEasyExcel\\itzhouq-poi"
    @Test
    public void testForMula() throws IOException {
        FileInputStream fileInputStream = new FileInputStream(PATH + "/公式.xls");
        Workbook workbook = new HSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);

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

        // 拿到計算公式
        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); // SUM(A2:A4)

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

3、EsayExcel 操作

官方文檔很詳細,可以根據文檔快速入門 https://www.yuque.com/easyexcel/doc/easyexcel

導入依賴

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

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

寫入測試

根據官方文檔的測試代碼: https://www.yuque.com/easyexcel/doc/write

1、DemoData.java

package cn.itzhouq.easyexcel;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

import java.util.Date;

@Data
public class DemoData {
    @ExcelProperty("字符串標題")
    private String string;
    @ExcelProperty("日期標題")
    private Date date;
    @ExcelProperty("數字標題")
    private Double doubleData;
    /**
     * 忽略這個字段
     */
    @ExcelIgnore
    private String ignore;
}

2、測試寫入數據

package cn.itzhouq.easyexcel;

import com.alibaba.excel.EasyExcel;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EasyExcelTest {
    private List<DemoData> data() {
        List<DemoData> list = new ArrayList<DemoData>();
        for (int i = 0; i < 10; i++) {
            DemoData data = new DemoData();
            data.setString("字符串" + i);
            data.setDate(new Date());
            data.setDoubleData(0.56);
            list.add(data);
        }
        return list;
    }

    // 根據list 寫入 Excel
    /**
     * 最簡單的寫
     * <p>1. 創建excel對應的實體對象 參照{@link DemoData}
     * <p>2. 直接寫即可
     */
    @Test
    public void simpleWrite() {
        String PATH = "F:\\workspaces\\workspaces_idea\\POIAndEasyExcel\\EasyExcel\\";
        String fileName =PATH + System.currentTimeMillis() + ".xlsx";
        // 這里 需要指定寫用哪個class去寫,然后寫到第一個sheet,名字為模板 然后文件流會自動關閉
        // 如果這里想使用03 則 傳入excelType參數即可
        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());

    }
}

最終結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM