-2
//NSString *csvString = @"S.No,Task,Date,Time";
//NSArray *csvArray=[csvString componentsSeparatedByString:@","];
// Create .csv file and save in Documents Directory.

NSArray *csvArray =[[NSArray alloc]initWithObjects:@"SNo",@"Task",@"Date",@"Time",nil]; //创建 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]; //最后保存路径(文件)

CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:fullPath atomic:NO];
NSInteger numberOfColumns = 4;
for (NSInteger currentIndex = 0; currentIndex < [csvArray count]; currentIndex++) {
    id field = [csvArray objectAtIndex:currentIndex];
    [csvWriter writeField:field];
    if ((currentIndex % numberOfColumns) == (numberOfColumns - 1)) {
        [csvWriter writeLine];
    }
}
[csvWriter release];
4

1 回答 1

0

CSV 文件基本上用于备份 iphone 联系人,它是一个 Excel 文件,为什么要制作 CSV 文件,如果需要,那么您必须根据您的 CSV 制作一个数组,为此您必须学习....这里是在 CSV 文件中写入文本并将其保存到文档目录中的代码....

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *FileName = [NSString stringWithFormat:@"%@/File.csv", documentsDirectory];
NSString *Content = [[NSString alloc] initWithFormat:@"%@", stringForCsv];
//stringForCsv is your string which you want to write in file.
[Content writeToFile:FileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];

谢谢你!

于 2012-06-16T12:01:13.990 回答