使用poi读写excel、向excel追加数据等,包括.xls和.xlsx文档

1、使用maven引入jar包

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.14</version>
        </dependency>

  实际引入的jar包为:

如果不使用maven方法引入jar包只需导入以下jar包

2、 向excel追加数据示例:

    public static void dealExcel(String in, String out) throws Exception {
        if (!in.equals(out)) {
           copyFile(in, out);
        }

        FileInputStream input = new FileInputStream(new File(out));
        Workbook wb = WorkbookFactory.create(input);
        System.out.println(wb.getClass());
        FileOutputStream output = new FileOutputStream(new File(out));
        Sheet sheet = wb.getSheetAt(0);

        int columnCount = -1;
        int rowCount = 0;
        for (Row row : sheet) {
            if (columnCount == -1) {
                columnCount = row.getLastCellNum();
            }

            if (row.getLastCellNum() == columnCount) {
                //增加列
                Cell last = row.createCell(columnCount);
                if (rowCount == 0) {
                    last.setCellValue("Test");
                } else {
                    last.setCellValue(rowCount);
                }
                rowCount++;
            }
        }
        
        ////添加行
        //Row row = sheet.createRow(sheet.getLastRowNum());
        //Cell cell = row.createCell(0);
        //cell.setCellValue("Test"); 

        output.flush();
        wb.write(output);
        wb.close();
        output.close();
    }
    public static void copyFile(String in, String out) throws Exception {
        InputStream inputStream = new FileInputStream(new File(in));

        File copy = new File(out);
        if (copy.exists()) {
            copy.delete();
        }
        copy.createNewFile();
        OutputStream outputStream = new FileOutputStream(copy);

        byte[] buffer = new byte[1024 * 4];
        while ((inputStream.read(buffer)) != -1) {
            outputStream.write(buffer);
        }

        inputStream.close();
        outputStream.close();
        
    }

猜你喜欢

转载自www.cnblogs.com/wushengwuxi/p/10752590.html
今日推荐