话不多说,直接撸代码 package com.example.util; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.IndexedColors; import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; /** * @program: boot * @description * @author: * @create: 2020-08-23 15:43 **/ public class ExeclUtilTest { /** * 设置豆绿色填充色 * * @throws IOException */ @Test public void exportExcel() throws IOException { // 创建HSSFWorkbook对象 HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); // 定义 loginusers 的sheet页 HSSFSheet sheet = hssfWorkbook.createSheet("loginusers"); // 创建第一行对象 HSSFRow HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell(0); cell.setCellValue("test1011"); // 豆绿色的rgb为(199,237,204) // 创建HSSFPalette对象 HSSFPalette palette = hssfWorkbook.getCustomPalette(); // 将绿色的rgb覆写为豆绿的rgb(199,237,204),这样绿色的索引17就代表了豆绿色的 // HSSFColor.GREEN.index获取绿色索引已过时,改用此IndexedColors.GREEN.getIndex()获取索引 palette.setColorAtIndex(IndexedColors.GREEN.getIndex(), (byte) 199, (byte) 237, (byte) 204); System.out.println(IndexedColors.GREEN.getIndex()); // 创建 HSSFCellStyle 对象 HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle(); // 设置单元格样式为豆绿色 cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); // 设置样式为填充,很重要,没有该设置,excel单元格将不会渲染填充 cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cell.setCellStyle(cellStyle); // 第二列设值 HSSFCell cell1 = row.createCell(1); cell1.setCellValue("test2"); // 第三列设值 HSSFCell cell2 = row.createCell(2); cell2.setCellValue("test3"); // 第四列设值 HSSFCell cell3 = row.createCell(3); cell3.setCellValue("test4"); // 通过类加载器设置导出路径 String path = getClass().getClassLoader().getResource("").getPath(); System.out.println(path); File file = new File(path + File.separator + "color.xls"); // hssfWorkbook 写入到文件 hssfWorkbook.write(file); System.out.println("success "); } }
Poi自定颜色操作单元格
最新推荐文章于 2023-07-06 15:29:16 发布