如何生成CSV文件?

时间:2013-04-16 13:44:10

标签: ios objective-c csv export

我将数据导出到excel它运行正常。 但我有一个小问题

我的输出导出如下:

enter image description here

我想要发生的是:

enter image description here

这是我要导出的代码:

-(void)exportCSV {

    NSArray * data = [NSArray arrayWithObjects:entries,keys, nil];
    NSLog(@"%@",data);
    csv =[NSMutableString string];
    for (NSArray * line in data) {
        NSMutableArray * formattedLine = [NSMutableArray array];
        for ( field in line) {
            BOOL shouldQuote = NO;
            NSRange r = [field rangeOfString:@","];
            //fields that contain a , must be quoted
            if (r.location != NSNotFound) {
                shouldQuote = YES;
            }
            r = [field rangeOfString:@"\""];
            //fields that contain a " must have them escaped to "" and be quoted
            if (r.location != NSNotFound) {
                field = [field stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
                shouldQuote = YES;
            }
            if (shouldQuote == YES) {
                [formattedLine addObject:[NSString stringWithFormat:@"\"%@\"\"%@\"", entries,keys]];
            } else {
                [formattedLine addObject:field];
            }
        }

        NSString * combinedLine = [formattedLine componentsJoinedByString:@";"];
        [csv appendFormat:@"%@\n", combinedLine];

        NSLog(@"%@",csv);
    }

}

1 个答案:

答案 0 :(得分:3)

以下是否符合您的要求?
请注意,我没有考虑报价,我把它留给你;)
另请注意,我假设entries.count == keys.count

- (void)exportCSV {    
    NSArray *keys = @[@"T", @"R", @"RTT"];
    NSArray *entries = @[@"-329180696", @"1243918297", @"-998693494"];
    NSMutableString *csv = [[NSMutableString alloc] initWithCapacity:0];
    for (int i = 0; i < entries.count; i++) {
        [csv appendFormat:@"%@;%@\n", keys[i], entries[i]];
    }
}

<强>输出:

  

吨; -329180696
  R等1243918297
  RTT; -998693494