从iOS中的数据数组创建csv文件

时间:2022-04-20 05:43:03

I want to write data from sql file to csv file. I have collected all data from sql file in an array and using for loop i am appending and writing data to .csv file. but it seems that it shows data in one line only it does not go to new line to create new row. I have used this for reference. This is my code :

我想将数据从sql文件写入csv文件。我已从数组中的sql文件中收集了所有数据并使用for循环,我将数据附加到.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]];      
    }    
}

5 个解决方案

#1


35  

This only writes one line because you rewrite the file every time you go through your loop. It is best to not writeData on the file until the loop has completed. I would also use an NSMutableString like this:

这只会写一行,因为每次循环都会重写文件。在循环完成之前,最好不要在文件上写入数据。我也会像这样使用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]];
}    

#2


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

#3


0  

Instead of :

代替 :

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

... just write :

... 写吧 :

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

Exactly same result for only one short line of code. ;o)

只有一行短代码的结果完全相同。 ; O)

#4


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

#5


0  

Try this it's working for me ,

试试这个对我有用,

If any one want to create .csv file in swift 3

如果有人想在swift 3中创建.csv文件

   // 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")
   }
  }

For more details you can refer Detail Answer

有关详细信息,请参阅详细解答

Hopes this will help to some one .

希望这对某些人有所帮助。

#1


35  

This only writes one line because you rewrite the file every time you go through your loop. It is best to not writeData on the file until the loop has completed. I would also use an NSMutableString like this:

这只会写一行,因为每次循环都会重写文件。在循环完成之前,最好不要在文件上写入数据。我也会像这样使用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]];
}    

#2


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

#3


0  

Instead of :

代替 :

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

... just write :

... 写吧 :

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

Exactly same result for only one short line of code. ;o)

只有一行短代码的结果完全相同。 ; O)

#4


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

#5


0  

Try this it's working for me ,

试试这个对我有用,

If any one want to create .csv file in swift 3

如果有人想在swift 3中创建.csv文件

   // 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")
   }
  }

For more details you can refer Detail Answer

有关详细信息,请参阅详细解答

Hopes this will help to some one .

希望这对某些人有所帮助。