Create csv file in iPhone programmatically

Create CSV file in IOS SDK - Tutorial (Objcetive C)

Introduction to how to create csv file in iPhone programmatically

Creating CSV (Comma Separated Values) or Excel file in IOS SDK is very easy. In this post, I am sharing a demo code for creating CSV (Comma Separated Values) or Excel file in IOS programmatically.

Tutorial is updated to swift: Click here for swift version

Jump to code

First, we will create our data with the help of NSMutableArray and NSMutableDictionary. Below is the code for creating dummy data for our CSV or Excel file.
    

employeeInfoArray  = [[NSMutableArray alloc]initWithCapacity:0];

    for (int i = 0;i<10;i++)
    {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
        [dict setValue:[NSString stringWithFormat:@”IDEMP%d”,i+1] forKey:@”EMPID”];
        [dict setValue:[NSString stringWithFormat:@”NameEMP%d”,i+1] forKey:@”EMPNAME”];
        [dict setValue:[NSString stringWithFormat:@”DEPP%d”,i+1] forKey:@”EMPDEP”];
        
        [employeeInfoArray addObject:dict];
        
    }
         
         [self createCSV];

NOTE: employeeInfoArray is declared in .h file.

In order to create CSV or excel file, we will use NSMutableString in which values are separated by     ‘ , ‘  values. Then we, will save our file to document directory.

Code for creating CSV or excel file:

-(void)createCSV
{

    NSMutableString *csvString = [[NSMutableString alloc]initWithCapacity:0];
    [csvString appendString:@”ID, NAME, DEPARTMENTnnn”];
    
    for (NSDictionary *dct in employeeInfoArray) {
        [csvString appendString:[NSString stringWithFormat:@”%@, %@, %@n”,[dct valueForKey:@”EMPID”],[dct valueForKey:@”EMPNAME”],[dct valueForKey:@”EMPDEP”]]];

    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@”%@/%@”, documentsDirectory, @”EmployeeRecords.csv”];

    [csvString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

OutPut:

CSV file created programmatically and then uploaded to Google drive
CSV file created programmatically and then uploaded to Google drive
CSV file created programmatically and then uploaded to Google drive and shown in Spreadsheet
CSV file created programmatically,  shown in Spreadsheet

 

Source Code:  Download

Note: Remove commas , so that accurate CSV can be generated.

Where to go from here 

In this post we learned how to create csv file in iPhone programmatically in ios sdk. If you have any questions then feel free to ask. Happy coding 🙂