我正在尝试使用 setFillBackgroundColor 方法设置背景颜色,但似乎有必要使用 setFillPattern 。但是使用 setFillPattern 方法我无法找到普通的 FillPatternType。
cellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
cellStyle.setFillPattern(HSSFCellStyle.SPARSE_DOTS);
我无法找到普通的 fillPatternType,如果我使用 NO_FILL 则背景颜色不适用。如果不使用setFillPattern,我无法看到setFillBackgroundColor的效果。
能否请您告诉我如何设置没有任何点、砖 block 、菱形或 DIAG 的纯背景颜色。
谢谢。
最佳答案
单元格内部使用图案填充。填充背景颜色是图案后面的颜色。填充前景色是图案的颜色。
要使用纯色填充单元格,您需要使用填充前景色和纯色图案。
参见Fills and colors 。
...
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setFillPattern(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;
public class CreateExcelCellFillColor {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
//Workbook workbook = new HSSFWorkbook();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("cell value");
cell.setCellStyle(cellStyle);
row.setHeightInPoints(50);
sheet.setColumnWidth(0, 50 * 256);
FileOutputStream out = null;
if (workbook instanceof HSSFWorkbook) {
out = new FileOutputStream("CreateExcelCellFillColor.xls");
} else if (workbook instanceof XSSFWorkbook) {
out = new FileOutputStream("CreateExcelCellFillColor.xlsx");
}
workbook.write(out);
out.close();
workbook.close();
}
}
结果:
关于java - 如何使用 apache poi 4.1.0 设置单元格的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154558/