简体   繁体   English

如何使用 apache pio 4.1.0 设置单元格的背景颜色

[英]how to set background color of a cell using apache pio 4.1.0

I am trying to set background color using setFillBackgroundColor method, but it seems necessary to use setFillPattern with it.我正在尝试使用 setFillBackgroundColor 方法设置背景颜色,但似乎有必要使用 setFillPattern 。 But using setFillPattern method I am not able to find the plain FillPatternType.但是使用 setFillPattern 方法我无法找到普通的 FillPatternType。

cellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
cellStyle.setFillPattern(HSSFCellStyle.SPARSE_DOTS);

I am not able to find the plain fillPatternType, If I use NO_FILL then the background color is not applying.我找不到普通的 fillPatternType,如果我使用 NO_FILL,则背景颜色不适用。 Without using setFillPattern, I am not able to see the effect of setFillBackgroundColor.如果不使用 setFillPattern,我无法看到 setFillBackgroundColor 的效果。

Could you please let me know how to set plain background color without any dots,brick,diamond or DIAG.您能否让我知道如何设置没有任何点、砖块、菱形或 DIAG 的纯背景色。

Thanks.谢谢。

Cell interior uses pattern fills.单元格内部使用图案填充。 The fill background color is the color behind the pattern.The fill foreground color is the color of the pattern.填充背景色是图案背后的颜色。填充前景色是图案的颜色。

To fill the cell using a plain color, you need using fill foreground color and solid pattern.要使用纯色填充单元格,您需要使用填充前景色和纯色图案。

See Fills and colors .请参阅填充和 colors

...
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
...

Complete example having cell fill and cell content:具有单元格填充和单元格内容的完整示例:

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();
 }
}

Result:结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM