Xcode - Create csv/spreadsheet file

2020-02-20 06:00发布

问题:

I have three arrays. The first array contains strings, same as the second, however the third one contains NSNumber's. Anyways, back on topic... how can I create a csv (which is an excel/numbers) file like a spreadsheet to contain this data. Is it possible?

These are my three arrays:

locationArray - contains many strings dateArray - contains many strings milesArray - contains many NSNumber's

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. 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.

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):

(MILES DATA IS JUST MADE UP)

回答1:


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