如何生成CSV文件?

6

我已经将数据导出到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
看起来你在data中的第一行是列标题,而后续行包含数据。由于你正在逐行处理事情,所以得到了预期的结果。要获取转置,您需要将所有数据读入数组的列中,然后按行读取它(或反之亦然)。或者,在首次打开Excel文件后,执行“全选-剪切-特殊粘贴-转置”。后者会更容易... - Floris
1
这个问题与Excel无关,这是一个“生成CSV”问题。 - rmaddy
1个回答

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

输出:

T;-329180696
R;1243918297
RTT;-998693494


如果我想传递T;-321455,5565656,4555,那么我该怎么做呢?我为第一个键传递了数组,但在csv T;中显示括号。 一, 二, 三 ) R;1243918297 RTT;-998693494 - DeviPhone26
()在这里是因为它是NSArray的描述方法实现。你可以展示一下你如何修改了我的答案代码,以及你的数据结构看起来像什么?(4555是从哪里来的?) - HAS
NSArray *keys = @[@"T", @"R", @"RTT"]; NSArray oneArr = @[@"one",@"two",@"three"]; NSString alertString = [oneArr componentsJoinedByString:@" "]; NSArray *entries = @[alertString, @"1243918297", @"-998693494"]; NSMutableString *csv = [[NSMutableString alloc] initWithCapacity:0]; for (int i = 0; i < entries.count; i++) { [csv appendFormat:@"%@;%@\n", keys[i], entries[i]]; } NSLog(@"csv %@",csv); - DeviPhone26
我想传递一个键的行数。 - DeviPhone26

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接