2013-04-16 199 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