Apache POI允许无涯教程同时在背景(background)和前景(foreground)中设置单个单元格的颜色。为此,它提供了有助于设置单元格颜色的方法。
在下面的示例中,将创建两个单元格并将颜色分别填充到背景和前景,参见示例。
链接:https://www.learnfk.comhttps://www.learnfk.com/apache-poi-word/apache-poi-excel-cell-color.html
来源:LearnFk无涯教程网
package poiexample; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ColorExample { public static void main(String[] args) throws FileNotFoundException, IOException { try (OutputStream fileOut = new FileOutputStream("Learnfk.xls")) { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("Sheet"); Row row = sheet.createRow(1); CellStyle style = wb.createCellStyle(); //设置背景颜色 style.setFillBackgroundColor(IndexedColors.GREEN.getIndex()); style.setFillPattern(FillPatternType.BIG_SPOTS); Cell cell = row.createCell(1); cell.setCellValue("Javatpoint"); cell.setCellStyle(style); //设置前景色 style = wb.createCellStyle(); style.setFillForegroundColor(IndexedColors.BLUE.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); cell = row.createCell(2); cell.setCellValue("A Technical Portal"); cell.setCellStyle(style); wb.write(fileOut); }catch(Exception e) { System.out.println(e.getMessage()); } } }
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)