Search code examples
iphoneobjective-ccsvsqliteexport-to-excel

How to export SQLite file into CSV file in iPhone SDK


In my app, I want to export a SQLite database file to CSV file..

Could you suggest me how to do this? Thanks.


Solution

  • First, you'll want to make sure that you're using FMDB to access the database, because people who use the SQLite C API directly in Objective-C are masochists. You can do that like this:

    FMDatabase *db = [[FMDatabase alloc] initWithPath:@"/path/to/db/file"];
    FMResultSet *results = [db executeQuery:@"SELECT * FROM tableName"];
    while([results nextRow]) {
      NSDictionary *resultRow = [results resultDict];
      NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:@selector(compare:)];
      //iterate over the dictionary
    }
    

    As for writing to a CSV file, well there's code for that too:

    #import "CHCSV.h"
    
    CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:@"/path/to/csv/file" atomic:NO];
    
    //write stuff
    [csvWriter closeFile];
    [csvWriter release];
    

    And to combine them, you'd do:

    FMDatabase *db = [[FMDatabase alloc] initWithPath:@"/path/to/db/file"];
    if (![db open]) {
      //couldn't open the database
      [db release];
      return nil;
    }
    FMResultSet *results = [db executeQuery:@"SELECT * FROM tableName"];
    CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initWithCSVFile:@"/path/to/csv/file" atomic:NO];
    while([results nextRow]) {
      NSDictionary *resultRow = [results resultDict];
      NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:@selector(compare:)];
      //iterate over the dictionary
      for (NSString *columnName in orderedKeys) {
        id value = [resultRow objectForKey:columnName];
        [csvWriter writeField:value];
      }
      [csvWriter writeLine];
    }
    [csvWriter closeFile];
    [csvWriter release];
    
    [db close];
    [db release];
    

    That will write the contents of the tableName table out to a CSV file.