APACHE POI 从 Java 中的 excel 获取准确的字体颜色 [英] APACHE POI getting exact font color from excel in Java

查看:55
本文介绍了APACHE POI 从 Java 中的 excel 获取准确的字体颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 excel 表中如何使用 java 中的 Apache POI 获取确切的字体颜色值.我尝试使用

In excel sheet how to get the exact Font color value using Apache POI in java. I tried to get font color by using

org.apache.poi.ss.usermodel.Font f = book.getFontAt(style.getFontIndex());短 clrIdx = f.getColor();

org.apache.poi.ss.usermodel.Font f = book.getFontAt(style.getFontIndex()); short clrIdx = f.getColor();

但它没有给出确切的颜色索引.获得此颜色值后,我必须在 PDFtable 中应用相同的颜色.在这里,我通过读取每个 excel 单元格格式并在 iText 中使用 pdf 创建相同的格式来进行 excel 到 pdf 的转换.

but it is not giving the exact color index. After getting this color value i have to apply the same color in the PDFtable. Here, I am doing the excel to pdf conversion by reading each excel cell format and creating the same using pdf in iText.

请帮帮我!!

提前致谢.

推荐答案

您需要从 Excel 字体颜色中获取 RGB 值.您可以通过几个步骤获得这些值.

You need to get the RGB values from the Excel font color. You can get those values in a couple of steps.

要获得适当的 POI Color 对象,您需要沿着 HSSF 或 XSSF 路径,提取适当的 HSSFColor 或 XSSFColor,然后从颜色中获取 RGB 值.

To get the appropriate POI Color object, you need to go down the HSSF or XSSF path, extract the appropriate HSSFColor or XSSFColor, then get the RGB values out of the color.

int red = 0;
int green = 0;
int blue = 0;
if (font instanceof HSSFont)
{
   HSSFColor color = ((HSSFFont) font).getHSSFColor(hssfWorkbook);
   // 0: red, 1: green, 2: blue
   short[] rgb = color.getTriplet();
   red = rgb[0];
   green = rgb[1];
   blue = rgb[2];
}
else if (font instanceof XSSFFont)
{
   XSSFColor color = ((XSSFFont) font).getXSSFColor();
   byte[] rgb = color.getRgb();
   // Bytes are signed, so values of 128+ are negative!
   // 0: red, 1: green, 2: blue
   red = (rgb[0] < 0) ? (rgb[0] + 256) : rgb[0];
   green = (rgb[1] < 0) ? (rgb[1] + 256) : rgb[1];
   blue = (rgb[2] < 0) ? (rgb[2] + 256) : rgb[2];
}
// Use the rgb values here.

然后您可以使用 rgb 值在 iText 中创建您的 BaseColor 对象.

Then you can use the rgb values to create your BaseColor object in iText.

更新:

有几个与在 XSSF 中提取颜色相关的 Apache POI 错误(对于 .xlsx 文件):

There are several Apache POI bugs filed related to extracting colors in XSSF (for .xlsx files):

#51222

#51236

#52079

#53274

当 XSSF 处理主题颜色时会出现这些错误.

These bugs show up when XSSF is dealing with theme colors.

这篇关于APACHE POI 从 Java 中的 excel 获取准确的字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆