Creating Excel (.xlsx) files in Cocoa

Austin picture Austin · Aug 27, 2010 · Viewed 17.8k times · Source

I'm writing a Cocoa application and I'm trying to export to the Excel XML format (ISO/IEC 29500-1) which is basically a zip file with a bunch of XML files in it named with a .xlsx extension.

I've tried generating AppleScript and using NSAppleScript to create the Excel file, which works, but is slow and the user has to have Excel installed on their machine.

I was able to create a simple .xlsx Excel file by writing the XML to files in Objective C and zipping them up and renaming the zip to .xlsx. Excel could open the file, but Numbers threw an error trying to open the file I created. It seems Excel must have implemented all (or most of) the ISO/IEC spec, while Numbers may only open the Excel flavored version.

How to create working Excel files using Cocoa and Objective-c?

Answer

Ashish Kakkad picture Ashish Kakkad · Feb 17, 2014

How about encapsulating HTML table in Excel file? I have checked that this works and I can open it with Excel.

NSURL * documentsDirectory = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].lastObject;
NSURL *file = [documentsDirectory URLByAppendingPathComponent:@"contacts.xls"];
NSString* string = @"<table><tr><td>FOO</td><td>BAR</td></tr></table>";
[string writeToFile:file.path atomically:YES encoding:NSUTF8StringEncoding error:nil];