我正在使用Apache POI阅读Excel工作表并使用iText库将其写入PDF。这已成功实现,但我为每个写入PDF的单元格获得默认黑色边框。因此我需要使用Apache POI获取单元格边框颜色,这可以使用返回短值的CellStyle类方法getBottomBorderColor()来实现。但是我需要一种方法将此值转换为RGB值,以便在将单元格写入PDF时我可以将RGB颜色值应用于单元格边框。
答案 0 :(得分:1)
CellStyle.getBottomBorderColor中的short
值是工作簿调色板中颜色的索引。这是一种用于存储旧二进制*.xls
Excel
格式的颜色的方法。因此,在apache poi
中,只有HSSFPalette只应在HSSF
中使用,而不能在XSSF
中使用。
在较新的*.xlsx
Excel
格式中,颜色将直接存储为十六进制值或作为主题颜色的引用。因此,对于XSSF
,XSSFCellStyle.getBottomBorderXSSFColor可以直接获取该颜色,而不是通过索引。
所以不幸的是,我们必须根据Excel
工作簿的类型来区分这两种方法。
示例:
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;
import java.io.FileInputStream;
class ExcelCellBorderColor{
public static void main(String[] args) throws Exception {
Workbook wb = WorkbookFactory.create(new FileInputStream("ExcelCellBorderColor.xlsx"));
//Workbook wb = WorkbookFactory.create(new FileInputStream("ExcelCellBorderColor.xls"));
String strrgb;
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
CellStyle style = cell.getCellStyle();
if (style instanceof XSSFCellStyle) {
XSSFColor xssfcolor = ((XSSFCellStyle)style).getBottomBorderXSSFColor();
if (xssfcolor != null) {
byte[] brgb = xssfcolor .getRGB();
strrgb = "R:"+String.format("%02X", brgb[0])+",G:"+String.format("%02X", brgb[1])+",B:"+String.format("%02X", brgb[2]);
System.out.println("Cell " + cell.getAddress() + " has border bottom color: " + strrgb);
}
} else if (style instanceof HSSFCellStyle) {
short colorindex = ((HSSFCellStyle)style).getBottomBorderColor();
HSSFPalette palette = ((HSSFWorkbook)wb).getCustomPalette();
HSSFColor hssfcolor = palette.getColor(colorindex);
if (hssfcolor != null) {
short[] srgb = hssfcolor.getTriplet();
strrgb = "R:"+String.format("%02X", srgb[0])+",G:"+String.format("%02X", srgb[1])+",B:"+String.format("%02X", srgb[2]);
System.out.println("Cell " + cell.getAddress() + " has border bottom color index: " + colorindex + ". This is " + strrgb);
}
}
}
}
wb.close();
}
}
答案 1 :(得分:-1)
您可以使用此颜色类
对此进行存档 CTScRgbColor scrgb = (CTScRgbColor)ch;
int r = scrgb.getR();
int g = scrgb.getG();
int b = scrgb.getB();
color = new Color(255 * r / 100000, 255 * g / 100000, 255 * b / 100000);