有没有人有一个示例应用或一些示例代码来在iOS上生成CSV文件?
答案 0 :(得分:15)
以下是生成CSV文件的简单代码:
NSArray *csvArray = [myTextView.text componentsSeparatedByString:@"\n"];
NSString *csvString = [csvArray componentsJoinedByString:@","];
NSLog(@"csvString:%@",csvString);
// Create .csv file and save in Documents Directory.
//create instance of NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
//create an array and store result of our search for the documents directory in it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//create NSString object, that holds our exact path to the documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"Document Dir: %@",documentsDirectory);
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.csv", @"userdata"]]; //add our file to the path
[fileManager createFileAtPath:fullPath contents:[csvString dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; //finally save the path (file)
答案 1 :(得分:4)
以下代码用于生成CSV。
NSMutableString *mainString=[[NSMutableString alloc]initWithString:@""];
for(int i=0;i<[commentArray count];i++ ) {
NSString *string=[[commentArray objectAtIndex:i]objectForKey:@"cmtName"];
string=[string stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
[mainString appendFormat:@"\"%@\"",string];
string=[[commentArray objectAtIndex:i]objectForKey:@"cmtDesc"];
string=[string stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
[mainString appendFormat:@",\"%@\"",string];
string=[[commentArray objectAtIndex:i]objectForKey:@"cmtType"];
string=[string stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
[mainString appendFormat:@",\"%@\"",string];
[mainString appendFormat:@",\"%@\"",string];
[mainString appendFormat:@"\n"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"Docment.conf"];
NSData* settingsData;
settingsData = [mainString dataUsingEncoding: NSASCIIStringEncoding];
if ([settingsData writeToFile:filePath atomically:YES])
NSLog(@"writeok");
要导入CSV,请使用此
答案 2 :(得分:2)
我的CHCSVParser将在OS X和iOS上读取和写入CSV文件。它附带了一些如何使用它的例子。