Does anyone have a sample app or some sample code to generate a CSV file on iOS?
Here is a simple code to generate CSV file :
NSArray *csvArray = [myTextView.text componentsSeparatedByString:@"\n"];
NSString *csvString = [csvArray componentsJoinedByString:@","];
NSLog(@"csvString:%@",csvString);
// Create .csv file and save in Documents Directory.
//create instance of NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
//create an array and store result of our search for the documents directory in it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//create NSString object, that holds our exact path to the documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"Document Dir: %@",documentsDirectory);
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.csv", @"userdata"]]; //add our file to the path
[fileManager createFileAtPath:fullPath contents:[csvString dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; //finally save the path (file)
My CHCSVParser will both read and write CSV files on OS X and iOS. It comes with some examples of how to use it.
Following code I used for generating CSV.
NSMutableString *mainString=[[NSMutableString alloc]initWithString:@""];
for(int i=0;i<[commentArray count];i++ ) {
NSString *string=[[commentArray objectAtIndex:i]objectForKey:@"cmtName"];
string=[string stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
[mainString appendFormat:@"\"%@\"",string];
string=[[commentArray objectAtIndex:i]objectForKey:@"cmtDesc"];
string=[string stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
[mainString appendFormat:@",\"%@\"",string];
string=[[commentArray objectAtIndex:i]objectForKey:@"cmtType"];
string=[string stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
[mainString appendFormat:@",\"%@\"",string];
[mainString appendFormat:@",\"%@\"",string];
[mainString appendFormat:@"\n"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"Docment.conf"];
NSData* settingsData;
settingsData = [mainString dataUsingEncoding: NSASCIIStringEncoding];
if ([settingsData writeToFile:filePath atomically:YES])
NSLog(@"writeok");
And for importing CSV you use this
https://github.com/davedelong/CHCSVParser