美文网首页
ios 创建CSV文件,并写入数据

ios 创建CSV文件,并写入数据

作者: 紫竹吟风 | 来源:发表于2017-11-03 11:32 被阅读0次

CSV文件可用excel软件打开,并可以转换成excel格式,所以对于重复且逻辑复杂的大量数据操作时,可以用程序来实现并保存为csv文件,之后通过转换就可以轻松搞定了!

下面是实现11000个设备mac地址写入:

-(void)creatCSV{
    NSString *filePath = [@"Users/hankangmac/Desktop" stringByAppendingPathComponent:@"model.csv"];
    NSLog(@"filePath = %@", filePath);
    
    [self createFile:filePath];
    [self writeCSV:filePath];
}


- (void)createFile:(NSString *)fileName {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:fileName error:nil];

    if (![fileManager createFileAtPath:fileName contents:nil attributes:nil]) {
        NSLog(@"不能创建文件");
    }
    
}

- (void)writeCSV:(NSString *)fileName {
//    NSString* sourcePaht = [[self class] createFile];
    
    NSFileHandle* fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
    //将节点调到文件末尾
    [fileHandle seekToEndOfFile];
    
    
    for(int i=0;i<11000;i++){
        
        NSInteger  num = i + 28282;
        NSString * numStr1 = [self ToHex:num];
        NSString * str1 = [numStr1 substringToIndex:2];
        NSString * str2 = [numStr1 substringFromIndex:2];

        NSString * str = [NSString stringWithFormat:@"18:7A:93:7E:%@:%@\n",str1,str2];
        NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
        //追加写入数据
        [fileHandle writeData:stringData];
    }

    [fileHandle closeFile];

}
//10进制转16进制
-(NSString *)ToHex:(NSInteger)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    NSInteger ttmpig;
    for (int i =0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%ld",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    return str;
}

相关文章

网友评论

      本文标题:ios 创建CSV文件,并写入数据

      本文链接:https://www.haomeiwen.com/subject/ddftmxtx.html