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

谁能解释使用Apche

poi中的Cellstyle将Excel表格(前景值或背景值)(rgb值或十六进制值)添加到Excelsheet(XSSF工作簿)时如何自定义颜色?

回答:

设置自定义颜色取决于Excel文件的类型(Office Open XML格式*.xlsx与BIFF格式*.xls)。apache

poi由于弃用,使用不同版本的可能会有所不同。

使用Office Open

XML格式,*.xlsx我们可以简单地使用XSSFColor的构造函数设置新颜色。在apache

poi 4.0.0XSSFColor(byte[] rgb, IndexedColorMap

colorMap)可以使用。IndexedColorMapnull如果没有其他颜色的地图应使用而不是默认的一个。

使用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();

}

}

以上是 使用Apache POI将自定义颜色添加到Excel工作表 的全部内容, 来源链接: utcz.com/qa/409970.html

回到顶部