TheLearner
TheLearner

Reputation: 19507

Generate CSV sample iphone app/code

Does anyone have a sample app or some sample code to generate a CSV file on iOS?

Upvotes: 2

Views: 6561

Answers (3)

DShah
DShah

Reputation: 9866

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)

Upvotes: 15

Dave DeLong
Dave DeLong

Reputation: 243156

My CHCSVParser will both read and write CSV files on OS X and iOS. It comes with some examples of how to use it.

Upvotes: 2

mandeep-dhiman
mandeep-dhiman

Reputation: 2535

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

Upvotes: 4

Related Questions