Using apache POI ... I used workbook.CreateCellStyle(), if after a while I needed to delete the CellStyle created ... How do I remove it from the workbook? I can see it still remains even if it is unused.
What I need is something like workbook.deleteCellStyle(cellStyle.getIndex());
getRow(0). removeCell(cell);
To delete multiple rows from a worksheet, call the deleteRows method of the Cells collection. The deleteRows method takes two parameters: Row index: the index of the row from where the rows will be deleted. Number of rows: the total number of rows that need to be deleted.
Judging from the source the following method deletes unused CellStyles:
org.apache.poi.hssf.usermodel.HSSFOptimiser.optimiseCellStyles(HSSFWorkbook)
As of r1391891, HSSFOptimiser will also remove un-used styles, in addition to removing duplicate cell styles.
So, grab yourself a recent nightly build / svn checkout build (or just wait for the 3.9-beta1 release in a month or so!), and then do something like:
NPOIFSFileSystem poifs = new NPOIFSFileSystem(new File("/path/to/excel/file.xls"));
HSSFWorkbook wb = new HSSFWorkbook(poifs.getRoot());
HSSFOptimiser.optimiseCellStyles(wb);
FileOutputStream fout = new FileoutputStream("optimised.xls");
wb.write(fout);
fout.close()
After that, optimsed.xls
will contain no duplicated cell styles, and no un-used cell styles. (You could easily put the optimise step at the end of creating the file, if it's not already existing)
Note - the HSSFOptimiser approach will only work for .xls files, not for XSSF .xlsx ones. It should be possible to generalise the approach with not too much work, but for now it's HSSF only....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With