Skip to content

Apache POI

1.1 介绍

Apache POI是一个处理Microsoft Office各种文件格式的开源项目,我们可以使用POI在Java程序中对Microsoft Office各种文件进行读写操作。

一般情况下使用POI处理Excel文件。

1.2 使用

  1. 导入POM文件

    xml
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
            </dependency>
  2. 代码开发

    写:

    java
        public static void write() throws Exception {
            // 1. 在内存中创建一个Excel文件
            XSSFWorkbook excel = new XSSFWorkbook();
            // 2. 创建一个sheet
            XSSFSheet sheet = excel.createSheet("info");
            // 3. 创建一个row (索引是从0开始的)
            XSSFRow row = sheet.createRow(0);
            // 4. 创建一个cell (索引是从0开始的)
            row.createCell(0).setCellValue("姓名");
            row.createCell(1).setCellValue("性别");
    
            row = sheet.createRow(1);
            row.createCell(0).setCellValue("Jack");
            row.createCell(1).setCellValue("男");
    
            // 5. 写入
            FileOutputStream outputStream = new FileOutputStream("D:\\info.xlsx");
            // 6. 输出到外存中
            excel.write(outputStream);
        }

    读:

    java
        /**
         * 通过POI读取Excel
         * @throws Exception
         */
        public static void read() throws Exception {
            FileInputStream inputStream = new FileInputStream("D:\\info.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheetAt(0);
            for (int row = 0; row <= sheet.getLastRowNum(); row++) {
                String s1 = sheet.getRow(row).getCell(0).getStringCellValue();
                String s2 = sheet.getRow(row).getCell(1).getStringCellValue();
                System.out.println(s1 + " " + s2);
            }
    
            excel.close();
            inputStream.close();
        }