如何将Core Data导出为CSV

时间:2012-05-13 13:33:45

标签: iphone ios xcode core-data export-to-csv

我想使用CHCSVParser将我的核心数据导出为CSV。我知道如何从实体中获取所有价值,但我不知道如何写入CSV。

有人可以教我如何使用CHCSVParser写入CSV吗?

// 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);        
}  

2 个答案:

答案 0 :(得分:8)

CHCSVWriter有几种构建CSV文件的方法:

-writeField:接受一个对象并将其-description(在被正确转义后)写入CSV文件。如有必要,它还会写字段分隔符(,)。你可以传递一个空字符串(@“”)或nil来写一个空字段。

-writeFields:接受逗号分隔且未终止的对象列表,并将每个对象发送到-writeField:。

-writeLine用于终止当前的CSV行。如果您不调用-writeLine,那么所有CSV字段都将在一行上。

-writeLineOfFields:接受以逗号分隔且未终止的对象列表,将每个对象发送到-writeField:,然后调用-writeLine。

-writeLineWithFields:接受一个对象数组,将每个对象发送到-writeField:,然后调用-writeLine。

-writeCommentLine:接受一个字符串,并将其作为CSV样式的注释写入文件。

除了写入文件外,还可以初始化CHCSVWriter,以便直接写入NSString

像这样的东西对你有用。

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);

答案 1 :(得分:8)

上面的答案似乎已被弃用,作者用另一个似乎取代了该方法。 这对我有用,希望它有所帮助:

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];