iOS 将数据写到csv文件

本文介绍了一个iOS应用中将CoreData存储的学生数据导出为CSV文件的过程。首先通过创建文件并删除旧文件,然后利用NSOutputStream写入文件头和学生数据。每个学生数据包含编号和姓名,数据以CSV格式存储,方便用Excel等软件打开查看。

有这么一个需求,需要将程序中的数据信息写到csv文件中,可以使用excel等软件方便浏览。

总结以下实现过程。

使用到CoreData,界面布局如下:

在.m文件中声明私有方法:

- (void)createFile:(NSString *)fileName;

- (void)exportCSV:(NSString *)fileName;

- (NSArray *)queryStudents;


关联方法:

- (IBAction)inputData:(id)sender {

    

    AppDelegate *app = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context = app.managedObjectContext;

    

     

    Student *stu = (Student *)[NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];

    stu.name = self.nameTextField.text;

    stu.num = self.numTextField.text;

    

    

    NSError *error = nil;

    [context save:&error];

    

    

    self.nameTextField.text = @"";

    self.numTextField.text = @"";

}


- (IBAction)makeCSV:(id)sender {

    

    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);

    NSString *docementDir = [documents objectAtIndex:0];

    NSString *filePath = [docementDir stringByAppendingPathComponent:@"student.csv"];

    NSLog(@"filePath = %@", filePath);    

    

    [self createFile:filePath];

    [self exportCSV:filePath];

}



私有方法:

- (void)createFile:(NSString *)fileName {

    

    NSFileManager *fileManager = [NSFileManager defaultManager];

    [fileManager removeItemAtPath:fileName error:nil];

    

    

    if (![fileManager createFileAtPath:fileName contents:nil attributes:nil]) {

        NSLog(@"不能创建文件");

    }

     

}


- (void)exportCSV:(NSString *)fileName {

    

    

    NSOutputStream *output = [[NSOutputStream alloc] initToFileAtPath:fileName append:YES];

    [output open];

    

    

    if (![output hasSpaceAvailable]) {

        NSLog(@"没有足够可用空间");

    } else {

        

        NSString *header = @"学好,姓名\n";

        const uint8_t *headerString = (const uint8_t *)[header cStringUsingEncoding:NSUTF8StringEncoding];

        NSInteger headerLength = [header lengthOfBytesUsingEncoding:NSUTF8StringEncoding];

        NSInteger result = [output write:headerString maxLength:headerLength];

        if (result <= 0) {

            NSLog(@"写入错误");

        }

        

        

        NSArray *students = [self queryStudents];

        for (Student *stu in students) {

         

            NSString *row = [NSString stringWithFormat:@"%@,%@\n", stu.num, stu.name];

            const uint8_t *rowString = (const uint8_t *)[row cStringUsingEncoding:NSUTF8StringEncoding];

            NSInteger rowLength = [row lengthOfBytesUsingEncoding:NSUTF8StringEncoding];

            result = [output write:rowString maxLength:rowLength];

            if (result <= 0) {

                NSLog(@"无法写入内容");

            }

            

        }

        

        [output close];

    }

}


- (NSArray *)queryStudents {

    

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.managedObjectContext];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    fetchRequest.entity = entity;

    NSArray *students = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];

    

    return students;

}


一切看起来还不错,现在可以去沙盒路径下看看没有一个student.csv文件。
我装黑苹果的盘空间不多了,就没有装office了。在windows下打开,也许你看到的会是这样令人失望的内容。
    
 
来做点什么吧!!
1.请把excel关了。
2.打开excel软件。不是点击student.csv来打开,是直接运行excel!!!
3.选择  数据 >  自文本 > 选择student.csv文件


若你能看到这个界面,那么已经开成功了。
4.写一步,选择“逗号”为分隔符。一路确定。


一切安好!
 
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值