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

时间:2023-01-14 19:15:52

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

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

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

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

下面是引入的包:

org.apache.poi.ss.usermodel.WorkbookFactory
 
    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();
}