poi操作Excel并修改单元格背景色

废话不多说,直接来代码!!!

其中标红的才是重点!!!

代码中有时可以不用创建新文件, 如果报错的话可以通过创建新文件来进行操作(懒,没去找报错原因),不过原文件也会被修改。

操作之前做好备份!操作之前做好备份!操作之前做好备份!

下面是引入的包:

org. apache. poi. ss. usermodel.WorkbookFactory
org. apache. poi. ss. usermodel.CellStyle
 
    File file = new File("E:/test.xlsx");
    File newFile = new File("E:/test1.xlsx");
    if(!newFile.exists()) {
        try {
            newFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	    
    FileInputStream inputStream;
        try {
            inputStream = new FileInputStream(file);
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
                          
            //设置背景色 
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); 
           
            //修改单元格颜色
            Row row = sheet.getRow(0);
            Cell cell = row.getCell(1);
            cell.setCellStyle(cellStyle);
           
           
            //对修改后的Excel进行保存
             FileOutputStream excelFileOutPutStream = new FileOutputStream(newFile.getAbsolutePath());
             workbook.write(excelFileOutPutStream);
             excelFileOutPutStream.flush();
             excelFileOutPutStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (EncryptedDocumentException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }            

转载于:https://www.cnblogs.com/commissar-Xia/p/10298429.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值