I want to read the name given to a style applied to a cell in a xlsx document. I have extracted the file and in the xl/styles.xml i can find the style name:
After a lot of digging i found a solution. And i thought i would share it here. I still haven't found the name of the style. But i have found a way to get the color.
The CellStyle has an xf object witch holds a reference index for the used fill. You can get the fills from the Workbooks StylesTable.
The fill references colors in different ways depending on what color it is. Either it just has an rgb string that you can parse or it has a theme id and a tint value.
You can get the themes from the StylesTable just like the fills. and the theme has an rgb value. I am not sure how to apply the tint, but in my tests it hasn't been necessary.
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];
}
}