2012-04-12 83 views
14

我想從sql文件寫入數據到csv文件。我已經從一個數組中的sql文件中收集所有數據,並使用for循環,我將數據附加到數據並將其寫入.csv文件。但它似乎只在一行中顯示數據,但它不會到新行來創建新行。 我已使用this作爲參考。 這是我的代碼:從iOS中的數據陣列創建csv文件

-(NSString *)dataFilePath { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return [documentsDirectory stringByAppendingPathComponent:@"myfile.csv"]; 
} 

- (IBAction)saveAsFileAction:(id)sender {  
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) { 
     [[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil]; 
     NSLog(@"Route creato");   
    } 

    NSString *writeString;  
    for (int i=0; i<[dataArray count]; i++) {   
     writeString = [NSString stringWithFormat:@"%@, %@, %@, %@, %0.2f,",[[dataArray objectAtIndex:i]dates],[[dataArray objectAtIndex:i] time],[[dataArray objectAtIndex:i] category],[[dataArray objectAtIndex:i]place],[[dataArray objectAtIndex:i] amount]];   
     NSLog(@"writeString :%@",writeString);   
     NSFileHandle *handle; 
     handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ]; 
     //say to handle where's the file fo write 
     [handle truncateFileAtOffset:[handle seekToEndOfFile]]; 
     //position handle cursor to the end of file 
     [handle writeData:[writeString dataUsingEncoding:NSUTF8StringEncoding]];  
    }  
} 

回答

35

這只是因爲你每次都要經過你的循環時間重寫文件寫入一行。在循環完成之前,最好不要在文件上使用writeData。我也將使用像這樣的的NSMutableString:

- (IBAction)saveAsFileAction:(id)sender { 

    if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) { 
     [[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil]; 
     NSLog(@"Route creato"); 
    } 

    NSMutableString *writeString = [NSMutableString stringWithCapacity:0]; //don't worry about the capacity, it will expand as necessary 

    for (int i=0; i<[dataArray count]; i++) { 
     writeString = [writeString appendString:[NSString stringWithFormat:@"%@, %@, %@, %@, %0.2f, \n",[[dataArray objectAtIndex:i]dates],[[dataArray objectAtIndex:i] time],[[dataArray objectAtIndex:i] category],[[dataArray objectAtIndex:i]place],[[dataArray objectAtIndex:i] amount]]]; //the \n will put a newline in 
     } 
    } 

    //Moved this stuff out of the loop so that you write the complete string once and only once. 
    NSLog(@"writeString :%@",writeString); 

    NSFileHandle *handle; 
    handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ]; 
    //say to handle where's the file fo write 
    [handle truncateFileAtOffset:[handle seekToEndOfFile]]; 
    //position handle cursor to the end of file 
    [handle writeData:[writeString dataUsingEncoding:NSUTF8StringEncoding]]; 
}  
+0

謝謝。代碼工作完全沒問題..謝謝。 – 2012-04-12 07:27:47

+0

沒問題,很高興有幫助。 – sosborn 2012-04-12 07:37:14

+0

嘿,你知道如何從csv文件回收相同的數據嗎? @Prernachavan – iSwaroop 2013-06-04 11:18:01

5
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    NSString *root = [documentsDir stringByAppendingPathComponent:@"customers.csv"]; 

    NSString *temp; 

    temp = [NSString stringWithFormat:@"%@", [arrCustomersName objectAtIndex:0]]; 

    for (int i = 1; i < [arrCustomersName count]; i++) { 

     temp = [temp stringByAppendingFormat:@", %@", [arrCustomersName objectAtIndex:i]]; 
    } 

    [temp writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL]; 
0

相反的:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
NSString *documentsDir = [paths objectAtIndex:0]; 
NSString *root = [documentsDir stringByAppendingPathComponent:@"customers.csv"]; 

...只是寫:

NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:@"customers.csv"]; 

完全相同的結果只有一個短線的代碼。 ; O)

0
// For CSV File : 
     NSMutableString *stringToWrite = [[NSMutableString alloc] init]; 
[stringToWrite appendString:[NSString stringWithFormat:@"First Name,Last Name,Full Name,Phone Number, Email,Job, organizationName,Note\n\n"]]; 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     for(int i = 0 ;i<[Contact count];i++)  { 
      [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"firstName"] ]]; 
      [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"lastName"] ]]; 
      [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact valueForKey:@"userName"] objectAtIndex:i]]]; 
      [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"phoneNumber"] ]]; 
      [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"emailAddress"] ]]; 
      [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"jobTitle"] ]]; 
      [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"organizationName"] ]]; 
      [stringToWrite appendString:[NSString stringWithFormat:@"%@\n",[[Contact objectAtIndex:i] valueForKey:@"note"] ]]; 
     } 
     dispatch_async(dispatch_get_main_queue(), ^(void) { 
      NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); 
      NSString *documentDirectory=[paths objectAtIndex:0]; 
      NSString *strBackupFileLocation = [NSString stringWithFormat:@"%@/%@", documentDirectory,@"ContactList.csv"]; 
      [stringToWrite writeToFile:strBackupFileLocation atomically:YES encoding:NSUTF8StringEncoding error:nil]; 
     }); 
}); 
+0

感謝您的幫助,但答案是更好的解釋,而不僅僅是一整塊代碼 – goto 2016-12-29 13:08:38

0

試試這個它的工作對我來說,

如果任何一個想在迅速3

// MARK: CSV file creating 
    func creatCSV() -> Void { 

    let fileName = "Tasks.csv" 

    let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName) 
    var csvText = "Date,Task Name,Time Started,Time Ended\n" 

    for task in taskArr { 
     let newLine = "\(task.date),\(task.name),\(task.startTime),\(task.endTime)\n" 
     csvText.append(newLine) 
    } 

    do { 
     try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8) 
    } catch { 
     print("Failed to create file") 
     print("\(error)") 
    } 
    print(path ?? "not found") 
    } 
    } 

創建.csv文件,欲瞭解更多詳細信息,您可以參考Detail Answer

希望這對一些人有幫助。