如何使用Apache POI 4.1.0设置单元格的背景颜色

3
我正在尝试设置Excel文件中标题的背景颜色,但是单元格显示为黑色且无内容。我使用的是Apache POI 4.1.0和POI-OOXML 4.1.0。
以下是我尝试的代码:
XSSFWorkbook workbook = new XSSFWorkbook();

// Create a blank sheet
XSSFSheet sheet = workbook.createSheet("student Details");

XSSFCellStyle cellStyle = sheet.getWorkbook().createCellStyle();
cellStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.index);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

// This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] { "ID", "NAME", "LASTNAME" });
data.put("2", new Object[] { 1, "Pankaj", "Kumar" });
data.put("3", new Object[] { 2, "Prakashni", "Yadav" });
data.put("4", new Object[] { 3, "Ayan", "Mondal" });
data.put("5", new Object[] { 4, "Virat", "kohli" });

// Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
    // this creates a new row in the sheet
    XSSFRow row = sheet.createRow(rownum++);
    Object[] objArr = data.get(key);
    int cellnum = 0;
    for (Object obj : objArr) {
        // this line creates a cell in the next column of that row
        XSSFCell cell = row.createCell(cellnum++);
        cell.setCellStyle(cellStyle);
        if (obj instanceof String)
            cell.setCellValue((String) obj);
        else if (obj instanceof Integer)
            cell.setCellValue((Integer) obj);
    }
}

我在这里找到了一个类似的问题[如何使用apache pio 4.1.0设置单元格的背景颜色,但是答案没有帮助。

请问您能否指导我解决这个问题。

谢谢。


1
如我在链接的答案中所说:单元格内部使用图案填充。填充背景色是图案后面的颜色。填充前景色是图案的颜色。要使用纯色填充单元格,您需要使用填充前景CellStyle.setFillForegroundColor实心图案FillPatternType.SOLID_FOREGROUND。那么,如果您在代码中使用cellStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.index); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);而不是cellStyle.setFillBackgroundColor会发生什么? - Axel Richter
cs.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()) cs.setFillPatternType(CellStyle.SOLID_FOREGROUND) with poi-3.14 - levolutionniste
1个回答

22

如我在链接的回答中所述:单元格内部使用图案填充。填充背景颜色是图案后面的颜色。填充前景颜色是图案的颜色。要使用纯色填充单元格,需要使用填充前景颜色CellStyle.setFillForegroundColor和实心图案FillPatternType.SOLID_FOREGROUND

让我们再来一个完整的例子:

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.*;

public class CreateExcelCellFillColor2 {

 public static void main(String[] args) throws Exception {
  //Workbook workbook = new HSSFWorkbook(); 
  Workbook workbook = new XSSFWorkbook(); 

  // Create a blank sheet 
  Sheet sheet = workbook.createSheet("student Details"); 

  // Create header CellStyle
  Font headerFont = workbook.createFont();
  headerFont.setColor(IndexedColors.WHITE.index);
  CellStyle headerCellStyle = sheet.getWorkbook().createCellStyle();
  // fill foreground color ...
  headerCellStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.index);
  // and solid fill pattern produces solid grey cell fill
  headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  headerCellStyle.setFont(headerFont);

  // This data needs to be written (Object[]) 
  Map<String, Object[]> data = new TreeMap<String, Object[]>(); 
  data.put("1", new Object[]{ "ID", "NAME", "LASTNAME" }); 
  data.put("2", new Object[]{ 1, "Pankaj", "Kumar" }); 
  data.put("3", new Object[]{ 2, "Prakashni", "Yadav" }); 
  data.put("4", new Object[]{ 3, "Ayan", "Mondal" }); 
  data.put("5", new Object[]{ 4, "Virat", "kohli" }); 

  // Iterate over data and write to sheet 
  Set<String> keyset = data.keySet(); 
  int rownum = 0; 
  for (String key : keyset) { 
   // this creates a new row in the sheet 
   Row row = sheet.createRow(rownum++); 
   Object[] objArr = data.get(key); 
   int cellnum = 0; 
   for (Object obj : objArr) { 
    // this line creates a cell in the next column of that row 
    Cell cell = row.createCell(cellnum++); 
    // if rownum is 1 (first row was created before) then set header CellStyle
    if (rownum == 1) cell.setCellStyle(headerCellStyle);
    if (obj instanceof String) 
     cell.setCellValue((String)obj); 
    else if (obj instanceof Integer) 
     cell.setCellValue((Integer)obj); 
   } 
  } 

  for (int c = 0; c < 3; c++) {
   sheet.autoSizeColumn(c);
  }

  FileOutputStream out = null;
  if (workbook instanceof HSSFWorkbook) {
   out = new FileOutputStream("CreateExcelCellFillColor2.xls");
  } else if (workbook instanceof XSSFWorkbook) {
   out = new FileOutputStream("CreateExcelCellFillColor2.xlsx");
  }
  workbook.write(out);
  out.close();
  workbook.close();
 }
}

除了我的代码只在第一行使用标题单元格样式,并且因为黑色字体在50%灰度上不易读取,所以使用白色字体,你正在做的就是这样。

再次强调:灰色填充前景色和实心填充模式会产生实心灰色单元格填充。

结果:

enter image description here


当我尝试使用headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND)时,出现了一个错误,因为它期望的类型是"short",但接收到的类型是"FillPatternType"。 - Shai Alon
@Shai Alon:请不要使用旧版本的 apache poi。这段代码经过测试,在当前版本的 apache poi 上可以正常运行。 - Axel Richter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接