如何在iOS上将数据转换为CSV或HTML格式? [英] How to convert data to CSV or HTML format on iOS?

查看:200
本文介绍了如何在iOS上将数据转换为CSV或HTML格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用iOS中,我需要将一些数据导出为CSV或HTML格式。我如何做到这一点?

In my application iOS I need to export some data into CSV or HTML format. How can I do this?

推荐答案

RegexKitLite 带有一个例子,说明如何读取一个csv文件到NSArray的NSArray,并且反向是相当微不足道。

RegexKitLite comes with an example of how to read a csv file into an NSArray of NSArrays, and to go in the reverse direction is pretty trivial.

这将是这样的(警告:在浏览器中输入的代码):

It'd be something like this (warning: code typed in browser):

NSArray * data = ...; //An NSArray of NSArrays of NSStrings
NSMutableString * csv = [NSMutableString string];
for (NSArray * line in data) {
  NSMutableArray * formattedLine = [NSMutableArray array];
  for (NSString * field in line) {
    BOOL shouldQuote = NO;
    NSRange r = [field rangeOfString:@","];
    //fields that contain a , must be quoted
    if (r.location != NSNotFound) {
      shouldQuote = YES;
    }
    r = [field rangeOfString:@"\""];
    //fields that contain a " must have them escaped to "" and be quoted
    if (r.location != NSNotFound) {
      field = [field stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
      shouldQuote = YES;
    }
    if (shouldQuote == YES) {
      [formattedLine addObject:[NSString stringWithFormat:@"\"%@\"", field]];
    } else {
      [formattedLine addObject:field];
    }
  }
  NSString * combinedLine = [formattedLine componentsJoinedByString:@","];
  [csv appendFormat:@"%@\n", combinedLine];
}
[csv writeToFile:@"/path/to/file.csv" atomically:NO];

这篇关于如何在iOS上将数据转换为CSV或HTML格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆