2013-04-16 153 views
5

我有数据导出到Excel它工作正常。 但我有一个小问题如何生成CSV文件?

我的输出导出这样的:

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

回答

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

+0

如果我湾传递吨; -321455,5565656,4555然后我怎样才能做到这一点,我通过对第一密钥数组,但它示出了CSVŤ支架;( 一个, 两个) R等1243918297 RTT; -998693494 – DeviPhone26

+0

'()'在那里,因为它是'NSArray'的描述方法实现。你能告诉我你是如何改变我的答案中的代码以及你的数据结构是怎样的? ('4555'来自哪里? – HAS

+0

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 DeviPhone26