如何在iOS上将数据转换为CSV或HTML格式?

在我的应用程序iOS中,我需要将一些数据导出为CSV或HTML格式。 我怎样才能做到这一点?

RegexKitLite提供了一个如何将一个csv文件读入NSArray的NSArray的例子,并且在相反的方向进行是非常简单的。

它会是这样的(警告:在浏览器中键入的代码):

NSArray * data = ...; //An NSArray of NSArrays of NSStrings NSMutableString * csv = [NSMutableString string]; for (NSArray * line in data) { NSMutableArray * formattedLine = [NSMutableArray array]; for (NSString * field in line) { BOOL shouldQuote = NO; NSRange r = [field rangeOfString:@","]; //fields that contain a , must be quoted if (r.location != NSNotFound) { shouldQuote = YES; } r = [field rangeOfString:@"\""]; //fields that contain a " must have them escaped to "" and be quoted if (r.location != NSNotFound) { field = [field stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""]; shouldQuote = YES; } if (shouldQuote == YES) { [formattedLine addObject:[NSString stringWithFormat:@"\"%@\"", field]]; } else { [formattedLine addObject:field]; } } NSString * combinedLine = [formattedLine componentsJoinedByString:@","]; [csv appendFormat:@"%@\n", combinedLine]; } [csv writeToFile:@"/path/to/file.csv" atomically:NO]; 

一般的解决scheme是使用stringWithFormat:格式化每一行。 据推测,你正在写这个文件或套接字,在这种情况下,你会写每个string的数据表示(见dataUsingEncoding:到你创build它的文件句柄。

如果要格式化很多行,可能需要使用initWithFormat:和显式release消息,以避免在autorelease池中堆积过多的string对象而导致内存不足。

始终,始终记得在将它们传递给格式化方法之前正确地转义值

转义(和转义)一起编写unit testing是一件非常好的事情。 编写一个函数以CSV格式化单行,并有testing用例将其结果与正确的输出进行比较。 如果你有一个CSVparsing器,或者你需要一个,或者你只是想确保你的转义是正确的,那么编写unit testingparsing和unescaping以及转义和格式化。

如果您可以从包含CSV特殊字符和/或SQL特殊字符的任何组合的单个logging开始,对其进行格式化,parsing格式化的string,并以与您开始的logging相同的logging结束,那么您知道您的代码是好。

(以上所有内容同样适用于CSV和HTML,如果可能的话,可以考虑使用XHTML,以便使用XMLvalidation工具和parsing器,包括NSXMLParser。)

CSV – 逗号分隔值。

我通常只是迭代我的应用程序中的数据结构,每行输出一组值,逗号分隔的集合内的值。

 struct person { string first_name; string second_name; }; person tony = {"tony", "momo"}; person john = {"john", "smith"}; 

会看起来像

 tony, momo john, smith