iphone – Xcode – 创建csv /电子表格文件

前端之家收集整理的这篇文章主要介绍了iphone – Xcode – 创建csv /电子表格文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有三个阵列.第一个数组包含字符串,与第二个数组相同,但第三个数组包含NSNumber.无论如何,回到主题…如何创建一个csv(这是一个excel /数字)文件,如电子表格来包含这些数据.可能吗?

这些是我的三个数组:

locationArray – 包含许多字符串
dateArray – 包含许多字符串
milesArray – 包含许多NSNumber

但是每个数组包含相同数量的对象(例如在表视图中),您可以在NSDictionary中将数据分块.它就像一条链子.

那么它看起来像这样:

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

该字典将包含一个航班(此测试应用程序的功能是记录航班).因此,如果我使用for循环枚举这个并替换objectAtIndex:使用循环数字我可以获得许多航班词典.

现在您已了解我的数据结构的工作原理.我怎样才能创建一个excel /数字/电子表格CSV文件,例如这样(只是一个屏幕截图):

(里程数据刚刚建成)

解决方法

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 );
}

猜你在找的Xcode相关文章