gpt4 book ai didi

java - 使用 Apache POI 将自定义颜色添加到 Excel 工作表

转载 作者:行者123 更新时间:2023-11-30 02:00:15 26 4
gpt4 key购买 nike

任何人都可以解释如何使用 Apche poi 中的 Cellstyle 将自定义颜色(rgb 值或十六进制值)添加到 Excelsheet 工作表(无论是在前景还是背景)到 Excelsheet(XSSF 工作簿)?

最佳答案

设置自定义颜色取决于 Excel 文件的类型(Office Open XML 格式 *.xlsx 与 BIFF 格式 *.xls) 。由于弃用,使用不同版本的 apache poi 可能会有所不同。

使用 Office Open XML 格式*.xlsx,我们可以使用 XSSFColor 的构造函数简单地设置新颜色。 。在apache poi 4.0.0中可以使用XSSFColor(byte[] rgb, IndexedColorMap colorMap)。如果不使用其他颜色图来代替默认颜色图,则 IndexedColorMap 可以为 null

使用 BIFF 格式*.xls 仅索引颜色可用。但临时覆盖一些索引颜色是可能的。

以下代码显示两者都用于设置单元格的填充颜色。使用的自定义颜色是 RGB(112,134,156)。使用 HSSF(BIFF 格式 *.xls),索引颜色 HSSFColor.HSSFColorPredefined.LIME 将被临时覆盖。

请注意,以下内容经过测试并使用 apache poi 4.0.0 运行。不保证使用其他版本。

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

public class CreateExcelCustomColor {

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

Workbook workbook = new XSSFWorkbook();
//Workbook workbook = new HSSFWorkbook();

CellStyle cellcolorstyle = workbook.createCellStyle();
cellcolorstyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
byte[] rgb = new byte[]{(byte)112, (byte)134, (byte)156};
if (cellcolorstyle instanceof XSSFCellStyle) {
XSSFCellStyle xssfcellcolorstyle = (XSSFCellStyle)cellcolorstyle;
xssfcellcolorstyle.setFillForegroundColor(new XSSFColor(rgb, null));
} else if (cellcolorstyle instanceof HSSFCellStyle) {
cellcolorstyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIME.getIndex());
HSSFWorkbook hssfworkbook = (HSSFWorkbook)workbook;
HSSFPalette palette = hssfworkbook.getCustomPalette();
palette.setColorAtIndex(HSSFColor.HSSFColorPredefined.LIME.getIndex(), rgb[0], rgb[1], rgb[2]);
}

Sheet sheet = workbook.createSheet();
Cell cell = sheet.createRow(0).createCell(0);
cell.setCellStyle(cellcolorstyle);

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

}

}

关于java - 使用 Apache POI 将自定义颜色添加到 Excel 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53117806/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com