How to convert the NSMutableArray to CSV file on iPhone?

喜欢而已 提交于 2019-11-30 02:28:54

The CSV parser I wrote (http://github.com/davedelong/CHCSVParser) can parse CSV files into an NSArray of NSArrays (if you use the NSArray category included with the code), and I just added a method to the category to take one of those arrays and write it back to a CSV file.

So if you have an NSArray of NSArrays, then you can write it to a CSV file like this:

[myArray writeToCSVFile:myCSVFile atomically:YES];

If will gracefully fail if you do not pass an NSArray of NSArrays.

edit (prompted by @Aran's comment to the question) any object inside the subarrays will have its -description method written to the CSV file. If you want to write a series of objects to the file, with various properties as the fields of the CSV row, then my wrapper requires that the properties be placed in an array, and then that array will make up the row.

edit #2 I just updated my CSV parser to refactor the writing into it's own class. You can now do the following:

CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:outputFile atomic:NO];
NSInteger numberOfColumns = 3;
for (NSInteger currentIndex = 0; currentIndex < [csvArray count]; currentIndex++) {
  id field = [csvArray objectAtIndex:currentIndex];
  [csvWriter writeField:field];
  if ((currentIndex % numberOfColumns) == (numberOfColumns - 1)) {
    [csvWriter writeLine];
  }
}
[csvWriter release];

That will write your csvArray to the file whose path is outputFile, and the file will look like:

First Name,Last Name,Phone
Tom,Chan,123
Peter,Wong,456
Mary's,"Cho""w",789
NSString *csv = [myArray componentsJoinedByString: @","];

But be warned, this will not account for commas within the array's elements. You will need to define some escaping/unescaping technique for that, and that's entirely up to you to do.

Better approach is use xlsx instead of csv... It is easy:

You can use XlsxReaderWriter library...It is free and usefull for read & write!

  • Create a new project or open an existing project
  • Insert XlsxReaderWriter.xcodeproj as a sub project of your project
  • In your target Build phases insert XlsxReaderWriter as a target dependency
  • Add libXlsxReaderWriter.a and libz.tbd in Link binary with Libraries. Older systems can use libz.dylib instead of libz.tbd.
  • Add -all_load in Linking / Other Linker Flags in your project settings
  • Add the XlsxReaderWriter root directory path to User Header Search Paths and set it as recursive. For example, set the path to "$(SRCROOT)/XlsxReaderWriter/", not "$(SRCROOT)/XlsxReaderWriter/XlsxReaderWriter/".

Now, you can import BRAOfficeDocumentPackage.h in your code.

It also supports Swift:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!