Apache POI根据Excel模板填充数据

发布时间 2023-07-10 13:42:23作者: ashet

pom.xml导入依赖


(choose version) 参考 https://mvnrepository.com/

        <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)) {

                Workbook workbook = new XSSFWorkbook(fis);
                // 获取第一个sheet页
                Sheet sheet = workbook.getSheetAt(0);

                // 填充单元格

                sheet.getRow(0).getCell(0).setCellValue("hello world");

                workbook.write(fos);
            } catch (IOException e) {
                log.error("error --> xx文件 生成失败", e);
            }

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