Xcode – 创buildCSV /电子表格文件

我有三个数组。 第一个数组包含string,与第二个数组相同,但第三个数组包含NSNumber 。 无论如何,回到主题…我怎样才能创build一个CSV文件(这是一个Excel /数字)像电子表格文件来包含这些数据。 可能吗?

这是我的三个数组:

locationArray – 包含许多stringdateArray – 包含许多stringmilesArray – 包含许多NSNumber

但是每个数组都包含相同数量的对象(例如在表格视图中),您可以将这些数据拼凑在一个NSDictionary 。 它就像一个链条。

那么它看起来像这样:

 NSDictionary *firstFlight = [NSDictionary dictionaryWithObjectsAndKeys:[locationArray objectAtIndex: 0], @"FlightName", [dateArray objectAtIndex: 0], @"FlightDate", [milesArray objectAtIndex: 0], @"FlightMiles", nil]; 

该字典将包含一个航class(这个testing应用程序的function是logging航class)。 所以,如果我使用for循环枚举这个for并replaceobjectAtIndex:与循环的数字,我可以得到航class的许多字典。

现在你明白了我的数据结构是如何工作的。 我怎样才能创build一个Excel /数字/电子表格CSV文件看起来像这样(例如只是从它看起来像一个screencapture):

(英里数据只是制作完成)

在这里输入图像说明

 NSArray *firstArray, *secondArray, *thirdArray; NSMutableString *csv = [NSMutableString stringWithString:@"Name,Date,Miles"]; NSUInteger count = [firstArray count]; // provided all arrays are of the same length for (NSUInteger i=0; i<count; i++ ) { [csv appendFormat:@"\n\"%@\",%@,\"%d\"", [firstArray objectAtIndex:i], [secondArray objectAtIndex:i], [[thirdArray objectAtIndex:i] integerValue] ]; // instead of integerValue may be used intValue or other, it depends how array was created } NSString *yourFileName = @"your filename"; NSError *error; BOOL res = [csv writeToFile:yourFileName atomically:YES encoding:NSUTF8StringEncoding error:&error]; if (!res) { NSLog(@"Error %@ while writing to file %@", [error localizedDescription], yourFileName ); }
NSArray *firstArray, *secondArray, *thirdArray; NSMutableString *csv = [NSMutableString stringWithString:@"Name,Date,Miles"]; NSUInteger count = [firstArray count]; // provided all arrays are of the same length for (NSUInteger i=0; i<count; i++ ) { [csv appendFormat:@"\n\"%@\",%@,\"%d\"", [firstArray objectAtIndex:i], [secondArray objectAtIndex:i], [[thirdArray objectAtIndex:i] integerValue] ]; // instead of integerValue may be used intValue or other, it depends how array was created } NSString *yourFileName = @"your filename"; NSError *error; BOOL res = [csv writeToFile:yourFileName atomically:YES encoding:NSUTF8StringEncoding error:&error]; if (!res) { NSLog(@"Error %@ while writing to file %@", [error localizedDescription], yourFileName ); }