Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

iphone - how to export Core Data to CSV

I will like to use CHCSVParser to export my Core data to CSV. I know how to get all the value from entity, but I don't know how to write to CSV.

Can anybody teach me how to write to CSV with 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);        
}  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A CHCSVWriter has several methods for constructing CSV files:

-writeField: accepts an object and writes its -description (after being properly escaped) out to the CSV file. It will also write field seperator (,) if necessary. You may pass an empty string (@"") or nil to write an empty field.

-writeFields: accepts a comma-delimited and nil-terminated list of objects and sends each one to -writeField:.

-writeLine is used to terminate the current CSV line. If you do not invoke -writeLine, then all of your CSV fields will be on a single line.

-writeLineOfFields: accepts a comma-delimited and nil-terminated list of objects, sends each one to -writeField:, and then invokes -writeLine.

-writeLineWithFields: accepts an array of objects, sends each one to -writeField:, and then invokes -writeLine.

-writeCommentLine: accepts a string and writes it out to the file as a CSV-style comment.

In addition to writing to a file, CHCSVWriter can be initialized for writing directly to an 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...