我想删除 XLS 的一些预定义样式 - 例如“好”。对于 XLSX 没有问题:创建新的 CTCellStyle(不幸的是通过反射)、setName("Good")、setBuiltinId(26) 和 setHidden(true) - 现在 Excel (2016) 不显示“Good”样式。我可以为 XLS 做这样的事情吗?
编辑
示例代码:
XLSX 的隐藏样式 - 没有问题:
StylesTable styleSource = xssfWorkbook.getStylesSource(); // xssfWorkbook is instance of XSSFWorkbook
try {
// get ctCellStyles (by reflection)
Field field = StylesTable.class.getDeclaredField("doc");
field.setAccessible(true);
Object obj = field.get(styleSource);
StyleSheetDocument ssd = (StyleSheetDocument) obj;
CTStylesheet ctStyleSheet = ssd.getStyleSheet();
CTCellStyles ctCellStyles = ctStyleSheet.getCellStyles();
// find style "Good"
for (int i = 0; i < ctCellStyles.sizeOfCellStyleArray(); i++) {
CTCellStyle ctCellStyle = ctCellStyles.getCellStyleArray(i);
if (ctCellStyle.getName().equals("Good")) {
XmlBoolean hiddenXml = XmlBoolean.Factory.newInstance();
hiddenXml.setStringValue("1");
ctCellStyle.xsetHidden(hiddenXml);
}
}
} catch (Exception e) {}
XLS 的隐藏样式:
如果工作簿中存在样式,我可以得到它,但如何将其设置为“隐藏”?
try {
// get InternalWorkbook (by reflection)
Field field = HSSFWorkbook.class.getDeclaredField("workbook");
field.setAccessible(true);
Object iwb = field.get(hssfWorkbook); // hssfWorkbook is instance of HSSFWorkbook
InternalWorkbook internalWorkbook = (InternalWorkbook) iwb;
// find style "Good"
for (int xfIndex = 0; xfIndex < internalWorkbook.getNumRecords(); xfIndex++) {
// try to get every record as StyleRecord from internalWorkbook
StyleRecord styleRecord = internalWorkbook.getStyleRecord(xfIndex);
if (styleRecord != null && styleRecord.getName() != null) {
if (styleRecord.getName().equals("Good")) {
new DebugUtil(styleRecord.getName());
// TODO set here sth like "hidden" for styleRecord or maybe:
// get style with current id from workbook
HSSFCellStyle hssfCellStyle = hssfWorkbook.getCellStyleAt((short) xfIndex); // workbook is instance of org.apache.poi.ss.usermodel.Workbook
// TODO set here sth like "hidden" for hssfCellStyle
}
}
}
} catch (Exception e) {}
即使我可以将样式标记为“隐藏”,还有其他问题:如果我从0
to迭代,internalWorkbook.getNumRecords()
我只会得到现有的样式。因此,如果我正在创建自己的工作簿,我可能应该创建新的 StyleRecord 和/或 HSSFCellStyle 并将其标记为“隐藏”。我试过这个:
int size = internalWorkbook.getSize();
StyleRecord newStyleRecord = internalWorkbook.createStyleRecord(size);
HSSFCellStyle newHssfCellStyle = hssfWorkbook.createCellStyle();
newHssfCellStyle.setAlignment((short) 3); // align right, for tests, to see difference between original and created "Good" style
newStyleRecord.setName("Good");
// TODO set here sth like "hidden" for newStyleRecord and/or for newHssfCellStyle
这是设置我自己的“好”风格的方式。如果我不这样做,Excel (2016) 将显示默认的“良好”样式。