简体   繁体   English

Xcode - 创建csv /电子表格文件

[英]Xcode - Create csv/spreadsheet file

I have three arrays. 我有三个阵列。 The first array contains strings, same as the second, however the third one contains NSNumber 's. 第一个数组包含字符串,与第二个数组相同,但第三个数组包含NSNumber Anyways, back on topic... how can I create a csv (which is an excel/numbers) file like a spreadsheet to contain this data. 无论如何,回到主题...如何创建一个csv(这是一个excel /数字)文件,如电子表格来包含这些数据。 Is it possible? 可能吗?

These are my three arrays: 这些是我的三个数组:

locationArray - contains many strings dateArray - contains many strings milesArray - contains many NSNumber 's locationArray - 包含许多字符串dateArray - 包含许多字符串milesArray - 包含许多NSNumber的字符串

But each array contains the same amount of objects so (for example in a table view) you can piece the data together in an NSDictionary . 但是每个数组包含相同数量的对象(例如在表视图中),您可以在NSDictionary中将数据分块。 It is like a chain. 它就像一条链子。

So then it would look like this: 那么它看起来像这样:

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

And that dictionary would contain a flight (the functionality of this test app is to log flights). 该字典将包含一个航班(此测试应用程序的功能是记录航班)。 So if I enumerated this using a for loop and replaced objectAtIndex: with the looped number I could get many dictionaries of the flights. 因此,如果我使用for循环枚举这个并替换objectAtIndex:使用循环数字我可以获得许多航班词典。

Now that you understand how my data structure works. 现在您已了解我的数据结构的工作原理。 How can I create an excel/numbers/spreadsheet CSV file to look like this for example (just a screencapture from what it could look like): 我怎样才能创建一个excel /数字/电子表格CSV文件,例如这样(只是一个屏幕截图):

(MILES DATA IS JUST MADE UP) (里程数据刚刚建成)

在此输入图像描述


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM