当前位置:网站首页>通过POI追加数据到excel中小案例

通过POI追加数据到excel中小案例

2022-07-05 19:12:00 lang20150928

当前poi的版本为

<poi.veriosn>4.1.2</poi.veriosn>

相关依赖

      <!-- apache POI for xls -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.veriosn}</version>
        </dependency>
        <!-- apache POI for xlsx -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.veriosn}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>${poi.veriosn}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>${poi.veriosn}</version>
        </dependency>

案例代码

   public static void main(String[] args) throws IOException {
    
        String fileName = "D:\\data\\excel\\workbook.xls";
        File file = new File(fileName);
        if (file.exists()) {
    
            FileUtils.forceDelete(file);
        }
        // 首先创建一个空的excel
        try (Workbook wb = WorkbookFactory.create(false)) {
    
            Sheet wbSheet = wb.createSheet();
            Row row = wbSheet.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue("First Row");
            try (FileOutputStream fileOut = new FileOutputStream(fileName)) {
    
                wb.write(fileOut);
            }
        }

        for (int i = 0; i < 10; i++) {
    
            // 根据指定的流创建excel
            try (Workbook wb = WorkbookFactory.create(new FileInputStream(fileName))) {
    
                Sheet wbSheet = wb.getSheetAt(0);
                Row row = wbSheet.createRow(i + 1);
				Cell cell = row.createCell(i);
                cell.setCellValue("Hello World!" + i);
                try (FileOutputStream fileOut = new FileOutputStream(fileName)) {
    
                    wb.write(fileOut);
                }
            }
        }
    }

结果如下所示(后面的Hello World都是通过追加的方式添加的)
在这里插入图片描述

原网站

版权声明
本文为[lang20150928]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_37607945/article/details/125624579