POI用已有模板(xlsx后缀)修改字段内容

这篇博客介绍了如何利用Java的POI库,针对已有的xlsx模板文件,精确修改特定列的内容。特别强调了在处理多列合并时,应使用被合并列首列的索引来设置值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java代码

 try {
            Map beans = new HashMap(1);
            beans.put("name",conName);
           String srcFilePath = Thread.currentThread().getContextClassLoader().getResource("excel/picture.xlsx").getPath();
           //Thread.currentThread().getContextClassLoader().getResource("pdf/picturePdf.pdf").getPath();
            String fileName = "工程质量巡检记录表";
            String desFilePath = "E:/fy/" + fileName;

            FileInputStream in =new FileInputStream(srcFilePath);
            //读取excel模板
            XSSFWorkbook wb = new XSSFWorkbook(in);
            //读取了模板内所有sheet内容
            XSSFSheet sheet = wb.getSheetAt(0);
            //修改需要改的字段
            sheet.getRow(1).getCell(0).setCellValue("工程项目名称:"+conName);
            String downloadFileName=new String(fileName.getBytes("utf-8"),"iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename="+downloadFileName+".xlsx");
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //将excel写入到输出流中
            wb.write(os);
            os.flush();
            os.close();
        }  catch (Exception e) {
            e.printStackTrace();
            code=31500;
        }

特别注意:sheet.getRow(1).getCell(0).setCellValue("工程项目名称:"+conName);

getCell中的数字必须是要修改的列数,如果是多列合并,取被合并列的第一列的列数,否则不会赋值到你想要的地方

 

pom

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值