Convert a CSV into a Plist file
Here’s some code from awhile back. It’ll take a CSV and turn it into a Plist file.
The structure works like this:
The first row of your CSV is considered to be the header. The code will use content from the header row to create key names. For every subsequent row, the code will create a dictionary, associating the content of each column with the key names from the header. The dictionaries live in an array which is written out to a Plist file.
This is handy if you’ve got a bunch of spreadsheet-type data you’d like to use as the basis for a static reference in your app. Say, data about the periodic table, airport listings, trivia questions, whatever. You can sift and sort your data in a user-friendly environment like Numbers or Excel, then dump it out to CSV and put this code to work.
It uses cCSVParse to read the CSV file.
// NSLog(@"Converting %@",pathAsString); CSVParser *parser = [CSVParser new]; [parser openFileWithPath:pathAsString]; NSMutableArray *csvContent = [parser parseFile]; [parser closeFile]; if (pathAsString != nil) { NSArray *keyArray = [csvContent objectAtIndex:0]; NSMutableArray *plistOutputArray = [NSMutableArray array]; NSInteger i = 0; for (NSArray *array in csvContent) { NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; NSInteger keyNumber = 0; for (NSString *string in array) { [dictionary setObject:string forKey:[keyArray objectAtIndex:keyNumber]]; keyNumber++; } if (i > 0) { [plistOutputArray addObject:dictionary]; } i++; } // NSLog(@"Plist output array %@", plistOutputArray); NSMutableString *mutableString = [NSMutableString stringWithString:pathAsString]; [mutableString replaceOccurrencesOfString:@".csv" withString:@".plist" options:nil range:NSMakeRange([mutableString length]-4, 4)]; NSURL *url = [NSURL fileURLWithPath:mutableString]; // NSLog(@"Write to URL %@",url); [plistOutputArray writeToURL:url atomically:YES]; }
That’s from a simple desktop app I built for the purpose. It takes the path of your CSV, via drag-and-drop, then spits out the Plist beside it. You can grab the source at Google Code. You can also download this compiled binary if you want to get crackin’ right away.
Ben January 3rd
Thanks! That’s really useful!
Jean-Denis March 14th
It doesn’t process UTF-8 files correctly.
Sonali April 19th
Hey,
Thanks a lot this is what i am searching for
Add Yours
YOU