19

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?

Shog9
  • 156,901
  • 35
  • 231
  • 235
Austin
  • 4,638
  • 7
  • 41
  • 60
  • 1
    You could check out the [MSDN documentation of the XLSX file format](http://msdn.microsoft.com/en-us/library/dd922181(v=office.12).aspx). May that is of help to you... – froeschli Aug 30 '10 at 06:04

3 Answers3

11

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];
Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
3

I've worked with the OpenOffice API and it works great. I would suggest you work with that to create your Excel files. If you don't have time time/patience to do that, a workaround could be to have 2 links to export files, the XLSX version hack for the Excels of the world and then a separate exported CSV file for the Numbers application.

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
JiminyCricket
  • 7,050
  • 7
  • 42
  • 59
2

Wikipedia offers some links to libraries, which would probably give you a good start.

If the Office Open XML format isn't a requirement, and you don't need overly complex files exported, I also suggest checking saving the files as stylesheet formatted HTML which Excel can also read. A simple way to learn how to format the HTML you want as a spreadsheet is creating the file in Excel, and saving it as HTML.

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Amitay Dobo
  • 1,380
  • 9
  • 11