Ensuring that spreadsheets created by xlsx4j can be opened by Quick Look and Numbers

Following on from an earlier post on simplifying the addition of text-only cells to an Excel worksheet using xlsx4j, here’s a brief addendum that allows Apple’s Quick Look to preview the spreadsheet and for it to opened in Numbers (Apple’s spreadsheet package for OS X and iOS).

In short, Excel’s requirement for a “minimum viable OOXML spreadsheet” seems to be less stringent than Apple’s and, as such, following the steps outlined in the previous post would result in a spreadsheet that could be opened in Excel, but not in Quick Look or Numbers.

Thankfully, the fix is quite straightforward; it transpires that Apple’s software can’t open the spreadsheet if the /xl/styles.xml “part” is missing from the spreadsheet. Even an empty stylesheet is sufficient:

SpreadsheetMLPackage pkg = SpreadsheetMLPackage.createPackage();
WorksheetPart sheet = pkg.createWorksheetPart(new PartName("/xl/worksheets/sheet1.xml"), "Sheet 1", 1);
SheetData sheetData = sheet.getContents().getSheetData();

// Add a minimal stylesheet to the package
Styles styles = new Styles(new PartName("/xl/styles.xml"));
CTStylesheet ss = Context.getsmlObjectFactory().createCTStylesheet();
styles.setJaxbElement(ss);
pkg.getWorkbookPart().addTargetPart(styles);

Row titleRow = Context.getsmlObjectFactory().createRow();
titleRow.setHt(22.0);
titleRow.setCustomHeight(Boolean.TRUE);
Cell headerCell = this.newCellWithInlineString("Sheet 1 Heading");

titleRow.getC().add(headerCell);
sheetData.getRow().add(titleRow);

pkg.save(new File("Example.xlsx"));

See the previous post for the implementation of the newCellWithInlineString method. It’s also worth noting that the getJaxbElement() method on the WorksheetPart class has been deprecated since the last post and replaced with getContents(), as above.

Leave a Reply

Your email address will not be published. Required fields are marked *