poi设置单元格背景颜色

时间:2026-02-13 21:52:41

1、准备工作:下载poi插件,并且部署到项目下面,例子使用的是3.17版本。

poi设置单元格背景颜色

2、导出一个人员Excel表格,代码如下,制作例子说明,可以直接复制:

public static void main(String[] args) throws IOException {

HSSFWorkbook book = new HSSFWorkbook();

HSSFSheet sheet = book.createSheet("Info");

HSSFRow header = sheet.createRow(0);

header.createCell(0).setCellValue("序号");

   header.createCell(1).setCellValue("学号");

   header.createCell(2).setCellValue("姓名");   

   header.createCell(3).setCellValue("年龄");

   header.createCell(4).setCellValue("人员标编号");   

   header.createCell(5).setCellValue("地址");

   header.createCell(6).setCellValue("电话");

   

   header = sheet.createRow(1);

header.createCell(0).setCellValue("1");

   header.createCell(1).setCellValue("1");

   header.createCell(2).setCellValue("张三");   

   header.createCell(3).setCellValue("18");

   header.createCell(4).setCellValue("00001");   

   header.createCell(5).setCellValue("一街二号");

   header.createCell(6).setCellValue("1234567890");

       

   FileOutputStream fos;

try {

fos = new FileOutputStream("d:/test.xls");

book.write(fos);

fos.close();   

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

   

}

poi设置单元格背景颜色

3、在 FileOutputStream fos;上面添加代码:

CellStyle style = book.createCellStyle();    

style.setFillPattern(FillPatternType.SOLID_FOREGROUND);    

style.setFillForegroundColor(IndexedColors.AQUA.index);

header.getCell(0).setCellStyle(style);

poi设置单元格背景颜色

1、在 FileOutputStream fos;上面添加代码:

CellStyle style = book.createCellStyle();

HSSFPalette palette = book.getCustomPalette();     

palette.setColorAtIndex((short)9, (byte) 220, (byte) 20, (byte) 60);  

style.setFillPattern(FillPatternType.SOLID_FOREGROUND);   

style.setFillForegroundColor((short)9);  

header.getCell(0).setCellStyle(style);

     

style = book.createCellStyle();

palette = book.getCustomPalette();

 //颜色代码:139,0,139,    10表示索引,设置索引

palette.setColorAtIndex((short)10, (byte) 139, (byte) 0, (byte) 139);  

style.setFillPattern(FillPatternType.SOLID_FOREGROUND);   

//使用颜色索引

style.setFillForegroundColor((short)10);  

header.getCell(1).setCellStyle(style);

poi设置单元格背景颜色

© 2026 海能知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com