lundi 4 mai 2015

Export Column Headers to csv using FMDB and CHCSVWriter

I've created an app that I'm storing data in a SQLite db using FMDB.

I'm exporting some Tables from the db to a csv using CHCSVWriter.

What's the best method for exporting the column header row? Should I loop once using the 'orderedKeys' and write 'columnName' first then move to writing the content?

Code

FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[db open];
FMResultSet *results = [db executeQuery:@"SELECT * FROM tblScores"];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *document = [[NSString alloc] initWithFormat:@"%@/demo.csv", documentsDirectory];

CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initForWritingToCSVFile:document];

while([results next]) {
    NSDictionary *resultRow = [results resultDictionary];
    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 finishLine];
}
[csvWriter closeStream];

Aucun commentaire:

Enregistrer un commentaire