Apache POI根据Excel模板填充数据

pom.xml导入依赖

(choose version) 参考 MVN REPOSITORY

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>
        // templateFilePath--excel模板路径  targetFilePath--目标excel路径
        try (FileInputStream fis = new FileInputStream(templateFilePath);
             FileOutputStream fos = new FileOutputStream(targetFilePath)) {
            
            // fis从本地文件读数据,并填充至Workbook对象
            Workbook workbook = new XSSFWorkbook(fis);
            
            // 获取第一个sheet页
            Sheet sheet = workbook.getSheetAt(0);
            
            // 第一行第一列处单元格,赋值
            sheet.getRow(0).getCell(0).setCellValue("hello world");
            
            // 将数据写入fos,生成本地文件
            workbook.write(fos);
        } catch (IOException e) {
            log.error("error --> xx文件 生成失败", e);
        }

templateFilePath、targetFilePath均为文件全路径,例如: xxdir/xxName.xlsx

posted @ 2023-07-10 13:40  Ashe|||^_^  阅读(467)  评论(0编辑  收藏  举报