Create csv file from array of data in iOS
cocoa-touch, csv, ios, ipad, objective-c
Solution
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:
- (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]];
}
Problem
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 : ``` -(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]]; } } ```