How to export master data to CSV

I want to use CHCSVParser to export my master data to CSV. I know how to get all the value from an entity, but I don’t know how to write in CSV.

Can anyone teach me how to write in CSV using CHCSVParser ?

 // Test listing all Infos from the store NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"NoteLog" inManagedObjectContext:context]; [fetchRequest setEntity:entity]; NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; for (NoteLog *noteInfo in fetchedObjects) { NSLog(@"Name: %@", noteInfo.city ); NSLog(@"Name: %@", noteInfo.country); NSLog(@"Name: %@", noteInfo.datetime); NSLog(@"Name: %@", noteInfo.notelatitude); NSLog(@"Name: %@", noteInfo.notelongtitude); NSLog(@"Name: %@", noteInfo.state); NSLog(@"Name: %@", noteInfo.text); } 
+4
source share
2 answers

A CHCSVWriter has several methods for creating CSV files:

-writeField: takes an object and writes its -description (after proper escaping) to a CSV file. He will also write a field delimiter (,) if necessary. You can pass an empty string (@ "") or nil to write an empty field.

-writeFields: takes a list of comma-delimited and nil-terminated objects and sends them to -writeField :.

-writeLine used to end the current CSV line. If you do not call -writeLine, then all of your CSV fields will be on the same line.

-writeLineOfFields: takes a list of comma-delimited and nil-terminated objects, sends them to -writeField :, and then calls -writeLine.

-writeLineWithFields: takes an array of objects, sends each of them to -writeField :, and then calls -writeLine.

-writeCommentLine: takes a line and writes it to a file as a CSV-style comment.

In addition to writing to a file, CHCSVWriter can be initialized to write directly to NSString .

Something like this should work for you.

 CHCSVWriter *writer = [[CHCSVWriter alloc] initForWritingToString]; for (NoteLog *noteInfo in fetchedObjects) { [writer writeLineOfFields:noteInfo.city, noteInfo.country, noteInfo.datetime, noteInfo.notelatitude, noteInfo.notelongtitude, noteInfo.state, noteInfo.text, nil]; } NSLog(@"My CSV File: %@",writer.stringValue); 
+8
source

The above answer seems deprecated; the author replaced the method with another. This worked for me, hope this helps:

 NSOutputStream *stream = [[NSOutputStream alloc] initToMemory]; CHCSVWriter *writer = [[CHCSVWriter alloc] initWithOutputStream:stream encoding:NSUTF8StringEncoding delimiter:',']; for (Type *instance in fetchedResults) { [writer writeLineOfFields:@[instance.propertyA, instance.B]]; } [writer closeStream]; NSData *buffer = [stream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; NSString *output = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding]; 
+8
source

All Articles