CSV
逗号分隔值 (Comma-Separated Values,CSV, 有时也称为字符分隔值, 因为分隔字符也可以不是逗号), 其文件以纯文本形式存储表格数据 (数字和文本).(: 来自百度百科)
CSV 其实就是一个纯文本, 那么对应到 Objective-C 中, 他就是一个 NSString, 对应到 Swift 中就是一个 String
举个
- sj_mino1001.jpg,715282,4FB55FE8
- sj_mino1002.jpg,471289,93203C5C
- sj_mino1003.jpg,451929,C4E80467
这个就是一个简单的 CSV 文件, 每个值之间用, 分割, 在一行数据结束的时候才换行.
CSV 读取
假设我们的项目中有一个 CSV 文件, 叫做 1
获取文件路径
NSString *path = [[NSBundle mainBundle]pathForResource:@"1" ofType:@"csv"];
将此文件转码为一个字符串
- NSError *error = nil;
- //GBK 编码
- NSString *fileContents = [NSString stringWithContentsOfFile:path encoding:0x80000632 error:&error];
- //UTF8 编码
- NSString *fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
切割字符串, 可以拿到每一行的数据
- // 取出每一行的数据
- NSArray *_allLinedStrings = [fileContents componentsSeparatedByString:@"\r\n"];
如果有表头可以对表头进行处理, 即对第一行数据进行处理
- __block NSInteger nameRow = 0;
- __block NSInteger phoneRow = 0;
- NSArray *firstLine = [_allLinedStrings[0] componentsSeparatedByString:@","];
- [firstLine enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
- NSString *line = obj;
- if ([line isEqualToString:@"客户名称"]){
- nameRow = idx;
- }
- else if ([line isEqualToString:@"手机号"]){
- phoneRow = idx;
- }
- }];
对数据进行处理
- [_allLinedStrings enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
- if (idx == 0) {
- }
- else{
- NSString *str = obj;
- NSArray *array = [str componentsSeparatedByString:@","];
- // 获取到某一行的数据, 切割这个字符串就可以拿到这一行的值, 然后在进行下一步的处理
- }
- }];
CSV 文件的写入
假设我们有一个 likee.CSV 需要放在 Documents 目录下
创建写入路径
- NSString *fileNameStr = @"likee.Csv";
- NSString *DocPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:fileNameStr];
2. 够造需要写入的数据
- NSString *str = @"11111,22222,33333,44444\n";
- NSMutableString *csvString = [NSMutableString string];
- for (int i = 0; i< 400; i ++) {
- [csvString appendString:str];
- };
3. 够造为 NSData, 并使用 NSData 进行文件的写入.
- NSData *data = [csvString dataUsingEncoding:NSUTF8StringEncoding];
- [data writeToFile:DocPath atomically:YES];
编码格式的坑
在 Mac 下文本的默认编码格式使用的是 UTF-8, 在 Windows 的 Excel 上, 对中文的处理是 GBK, 所以可能会造成乱码的问题. 如果读取文件是无法读出内容, 就和使用的编码格式有关. 所以建议先使用 UTF-8 进行解码, 如果无法显示内容, 再用 GBK 进行解码
- //UTF8 编码
- NSString *fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
- if(!fileContents){
- //GBK 编码
- fileContents = [NSString stringWithContentsOfFile:path encoding:0x80000632 error:&error];
- }
来源: http://www.jianshu.com/p/d3a2c92dbc82