I am trying to convert an existing XSSFWorkbook with a specific formatting (a custom table) to an HSSFWorkbook in order to save it as an .xls file.
For this, I am using the following method that copies the data from the XSSFWorkbook and pastes it into a new HSSFWorkbook, before trying to also copy the style. However I cannot use the cloneStyleFrom method as it only works from one XSSFCell to another.
Do you have an idea of how I could proceed to copy the style of each cell and apply it to the new, HSSF ones?
The alternative that I have thought about was to add an .xls file to my project's resources folder with a giant, empty table with the right formatting, that I would then fill with the data taken from the other workbook, and then programatically delete the extra columns and rows remained empty. But I do not really like this solution and wanted to be sure there was no other before implementing it.
public Workbook convert(XSSFWorkbook wb, File inpFn) throws InvalidFormatException,IOException {
XSSFWorkbook wbIn = wb;
Workbook wbOut = new HSSFWorkbook();
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(i);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK: break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
//styleOut.cloneStyleFrom(styleIn); Does not work from XSSFCell to HSSFCell
cellOut.setCellStyle(styleOut);
}
}
}
return wbOut;
}