java数据通过POI导入导出Excel文件

一、Excel导入导出的应用场景

1、数据导入:减轻录入工作量
2、数据导出:统计信息归档
3、数据传输:异构系统之间数据传输

二、POI简介(Apache POI)

1、什么是POI

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
HSSF - 提供读写Microsoft Excel格式档案的功能。(.xls)
XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。(.xlsx)
HWPF - 提供读写Microsoft Word格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读写Microsoft Visio格式档案的功能。

2、官网

http://poi.apache.org/
官网可以找到文档和每个版本的下载地址

示例:

1、创建一个普通的maven项目

项目名:excel-poi
2、pom中引入xml相关依赖

<dependencies>
    <!--xls-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.9</version>
    </dependency>
    <!--xlsx-->
    <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>

二、xls写-03和07的区别

03版Excel

public class ExcelWriteTest {
    @Test
    public void testWrite03() throws IOException {
        // 创建新的Excel 工作簿
        Workbook workbook = new HSSFWorkbook();
        // 在Excel工作簿中建一工作表,其名为缺省值 Sheet0
        //Sheet sheet = workbook.createSheet();
        // 如要新建一名为"会员登录统计"的工作表,其语句为:
        Sheet sheet = workbook.createSheet("会员登录统计");
        // 创建行(row 1)
        Row row1 = sheet.createRow(0);
        // 创建单元格(col 1-1)
        Cell cell11 = row1.createCell(0);
        cell11.setCellValue("今日人数");
        // 创建单元格(col 1-2)
        Cell cell12 = row1.createCell(1);
        cell12.setCellValue(666);
        // 创建行(row 2)
        Row row2 = sheet.createRow(1);
        // 创建单元格(col 2-1)
        Cell cell21 = row2.createCell(0);
        cell21.setCellValue("统计时间");
        //创建单元格(第三列)
        Cell cell22 = row2.createCell(1);
        String dateTime = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
        cell22.setCellValue(dateTime);
        // 新建一输出文件流(注意:要先创建文件夹)
        FileOutputStream out = new FileOutputStream("d:/excel-poi/test-write03.xls");
        // 把相应的Excel 工作簿存盘
        workbook.write(out);
        // 操作结束,关闭文件
        out.close();
        System.out.println("文件生成成功");
    }
}

07版Excel

@Test
public void testWrite07() throws IOException {
    // 创建新的Excel 工作簿
    Workbook workbook = new XSSFWorkbook();
     ......
    // 新建一输出文件流(注意:要先创建文件夹)
    FileOutputStream out = new FileOutputStream("d:/excel-poi/test-write07.xlsx");
    ......
}

注意:如果针对不同版本的Excel使用了不适合的类库,则会报告异常
org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]

三、大文件写-HSSF、XSSF和SXSSF

1、使用HSSF

缺点:最多只能处理65536行,否则会抛出异常
java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0…65535)

优点:过程中写入缓存,不操作磁盘,最后一次性写入磁盘,速度快

@Test
public void testWrite03BigData() throws IOException {
    //记录开始时间
    long begin = System.currentTimeMillis();
    //创建一个SXSSFWorkbook
    //-1:关闭 auto-flushing,将所有数据存在内存中
    Workbook workbook = new HSSFWorkbook();
    //创建一个sheet
    Sheet sheet = workbook.createSheet();
    //xls文件最大支持65536行
    for (int rowNum = 0; rowNum < 65536; rowNum++) {
        //创建一个行
        Row row = sheet.createRow(rowNum);
        for (int cellNum = 0; cellNum < 10; cellNum++) {//创建单元格
            Cell cell = row.createCell(cellNum);
            cell.setCellValue(cellNum);
        }
    }
    System.out.println("done");
    FileOutputStream out = new FileOutputStream("d:/excel-poi/test-write03-bigdata.xls");
    workbook.write(out);
    // 操作结束,关闭文件
    out.close();
    //记录结束时间
    long end = System.currentTimeMillis();
    System.out.println((double)(end - begin)/1000);
}

2、使用XSSF

缺点:写数据时速度非常慢,非常耗内存,也会发生内存溢出,如100万条
优点:可以写较大的数据量,如20万条

@Test
public void testWrite07BigData() throws IOException {
    //记录开始时间
    long begin = System.currentTimeMillis();
    //创建一个XSSFWorkbook
    Workbook workbook = new XSSFWorkbook();
    ......
        
    FileOutputStream out = new FileOutputStream("d:/excel-poi/test-write07-bigdata.xlsx");
    ......
}

3、使用SXSSF

优点:可以写非常大的数据量,如100万条甚至更多条,写数据速度快,占用更少的内存

注意:
过程中会产生临时文件,需要清理临时文件(C:\Users\helen\AppData\Local\Temp)
默认由100条记录被保存在内存中,如果查过这数量,则最前面的数据被写入临时文件
如果想自定义内存中数据的数量,可以使用new SXSSFWorkbook(数量)

@Test
public void testWrite07BigDataFast() throws IOException {
    //记录开始时间
    long begin = System.currentTimeMillis();
    //创建一个SXSSFWorkbook
    Workbook workbook = new SXSSFWorkbook();
   ......
    FileOutputStream out = new FileOutputStream("d:/excel-poi/test-write07-bigdata-fast.xlsx");
    workbook.write(out);
    // 操作结束,关闭文件
    out.close();
    //清除临时文件
    ((SXSSFWorkbook)workbook).dispose();
    //记录结束时间
    long end = System.currentTimeMillis();
    System.out.println((double)(end - begin)/1000);
}

SXSSFWorkbook-来至官方的解释:实现“BigGridDemo”策略的流式XSSFWorkbook版本。这允许写入非常大的文件而不会耗尽内存,因为任何时候只有可配置的行部分被保存在内存中。
请注意,仍然可能会消耗大量内存,这些内存基于您正在使用的功能,例如合并区域,注释…仍然只存储在内存中,因此如果广泛使用,可能需要大量内存。

一、xls读-03版和07版(java读取Excel文件)

1、03版Excel

public class ExcelReadTest {
    @Test
    public void testRead03() throws Exception{
        InputStream is = new FileInputStream("d:/excel-poi/商品表-03.xls");
        Workbook workbook = new HSSFWorkbook(is);
        Sheet sheet = workbook.getSheetAt(0);
        // 读取第一行第一列
        Row row = sheet.getRow(0);
        Cell cell = row.getCell(0);
        // 输出单元内容
        System.out.println(cell.getStringCellValue());
        // 操作结束,关闭文件
        is.close();
    }
}

2、07版Excel

@Test
public void testRead07() throws Exception{
    InputStream is = new FileInputStream("d:/excel-poi/商品表-07.xlsx");
    Workbook workbook = new XSSFWorkbook(is);
    ......
}

二、读取不同类型的数据

1、读取不同的数据类型

@Test
public void testCellType() throws Exception {
    InputStream is = new FileInputStream("d:/excel-poi/会员消费商品明细表.xls");
    Workbook workbook = new HSSFWorkbook(is);
    Sheet sheet = workbook.getSheetAt(0);
    // 读取标题所有内容
    Row rowTitle = sheet.getRow(0);
    if (rowTitle != null) {// 行不为空
        // 读取cell
        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) {// 行不为空
            // 读取cell
            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】");
                            //cellValue = String.valueOf(cell.getNumericCellValue());
                            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 Cell.CELL_TYPE_ERROR:
                            System.out.print("【数据类型错误】");
                            break;
                    }
                    System.out.println(cellValue);
                }
            }
        }
    }
    is.close();
}

2、计算公式

@Test
public void testFormula() throws Exception{
    InputStream is = new FileInputStream("d:/excel-poi/计算公式.xls");
    Workbook workbook = new HSSFWorkbook(is);
    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://2
            //得到公式
            String formula = cell.getCellFormula();
            System.out.print(formula);
            CellValue evaluate = formulaEvaluator.evaluate(cell);
            //String cellValue = String.valueOf(evaluate.getNumberValue());
            String cellValue = evaluate.formatAsString();
            System.out.println(cellValue);
            break;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43277087/article/details/105268195