我想读取应用于xlsx文档中单元格的样式的名称。 我已经解压缩了文件,在xl / styles.xml中我可以找到样式名称:
<cellStyles count="3">
<cellStyle xfId="2" builtinId="7" name="Currency [0]"/>
<cellStyle xfId="0" builtinId="0" name="Normal"/>
<cellStyle xfId="1" name="test style"/>
</cellStyles>
我想要的样式名称是“测试样式”。目前我有以下代码,我可以得到xfId而不是名称:
@Override
public String getName(Workbook table, XSSFCell cell, String value) {
XSSFCellStyle cellStyle = cell.getCellStyle();
CellColor cellColor = new CellColor(cellStyle);
int xfId = cellStyle.getCoreXf().getFillId();
//todo: fint name, not xfId
return null;
}
有没有人知道我是否可以获得poi的样式名称,以及我将如何进行呢?
如果无法做到这一点,我可以根据xfId获得背景颜色为rgb吗?
问候
答案 0 :(得分:2)
CellStyle有一个xf对象,它拥有使用过的填充的参考索引。您可以从Workbooks StylesTable获取填充。
填充以不同的方式引用颜色,具体取决于颜色。它只是一个你可以解析的rgb字符串,或者它有一个主题id和一个色调值。
您可以像填充一样从StylesTable获取主题。并且主题具有rgb值。我不知道如何应用色调,但在我的测试中没有必要。
private int red;
private int green;
private int blue;
public void loadRgb(XSSFWorkbook table, XSSFCellStyle variableStyle) {
long fillId = variableStyle.getCoreXf().getFillId();
StylesTable stylesSource = table.getStylesSource();
XSSFCellFill fill = stylesSource.getFillAt((int) fillId);
CTColor fgColor = fill.getCTFill().getPatternFill().getFgColor();
if (fgColor != null) {
if (fgColor.xgetRgb() != null) {
convert(fgColor.xgetRgb().getStringValue());
} else {
convert(stylesSource.getTheme().getThemeColor((int) fgColor.getTheme()).getRgb());
}
}
}
private void convert(String stringValue) {
// the string value contains an alpha value, so we skip the first 2 chars
red = Integer.valueOf(stringValue.substring(2, 4), 16).intValue();
green = Integer.valueOf(stringValue.substring(4, 6), 16).intValue();
blue = Integer.valueOf(stringValue.substring(6, 8), 16).intValue();
}
private void convert(byte[] rgb) {
if (rgb != null) {
// 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];
}
}
答案 1 :(得分:2)
我在寻找尚未得到答复的部分时发现了这个问题:您如何找到该风格的名称?
首先,似乎从XSSFCell返回的样式与cellStyle
中的styles.xml
部分无关。相反,它似乎是另一个名为cellStyleXfs
的部分。无论如何,我最终挖掘CT
样式来查找信息。
长话短说,下面的代码让我找到了样式的名称:
XSSFWorkbook wb = new XSSFWorkbook(...);
StylesTable stylesTable = wb.getStylesSource();
CTStylesheet ct = stylesTable.getCTStylesheet();
CTCellStyles cellStyles = ct.getCellStyles();
// Prints the count from: <cellStyles count="3516">
System.out.println("Number of CT styles: " + cellStyles.getCount());
for (CTCellStyle style : cellStyles.getCellStyleList()) {
// Prints the name
// Example: <cellStyle name="Note 2" xfId="3506"/>
// Prints: Note 2
System.out.println(style.getName());
}
但是,为了实现这一点,您必须使用ooxml-schemas.jar
而不是POI附带的精简版本(poi-ooxml-schemas.jar
)。我发现它here。否则,将找不到CTCellStyles
和CTCellStyle
等类(this e-mail thread讨论不同的选项)。