ios - 从 NSMutableArray 创建一个 csv

标签 ios objective-c csv plist

在我的应用程序中,我正在创建一个 .plist 文件,但我需要在 Excel 表格中使用我存储在这个 .plist 中的数据。我需要一种从这个 plist 中获取 csv 的方法。我试图在网上搜索,但我只找到了允许从 csv 创建 plist 的转换器。我想有一种方法可以直接从我的 iPad 应用程序生成 csv 文件。有谁知道这样做的方法吗?

更新:

+ (void)saveFileFromArray:(NSMutableArray *)promoArray {
    NSMutableString *target = [@"Nome,Cognome,E-mail,Data di nascita,Indirizzo,Città,Cap,Telefono\n" mutableCopy];

    for (NSDictionary *dict in promoArray) {
        [target appendFormat:@"%@,%@,%@,%@,%@,%@,%@,%@\n",dict[@"name"],dict[@"surname"],dict[@"email"],dict[@"birthdate"],dict[@"address"],dict[@"city"],dict[@"zip"],dict[@"phone"]];
    }
    NSError *error = nil;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"profiles.csv"];

    NSURL *url = [NSURL URLWithString:fileName];

    BOOL success = [target writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];

    if (!success) {
        NSLog(@"Errore: %@", error.localizedDescription);
    }
}

最佳答案

遍历数组,并将您想要的部分写入字符串。

带逗号的字符串会有很大帮助。回车也不错。

当字符串完成时。将其写入文件。

NSMutableString *target = [@"head1,head2,head3\n" mutableCopy];

for (NSDictionary *dict in array) {

    [target appendFormat:@"%@,%@,%@\n",dict[@"thing"],dict[@"otherthing"],dict[@"lemming"]];

}

NSError *error = NULL;

BOOL success = [target writeToURL:somewhere atomically:YES encoding:NSUTF8StringEncoding error:&error];

if (!success) {
    NSLog(@"oh no! - %@",error.localizedDescription);
}

该代码片段假定您有一个 NSDictionary 数组,但如果是其他内容,原理是相同的。

为每个对象打印出逗号分隔的字符串并以 CR 结尾。

在现实世界的数据中你必须要提防的是

  • 已包含逗号的描述。
  • 已经有 CR 的描述。

关于ios - 从 NSMutableArray 创建一个 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21939863/

相关文章:

iphone - UITableViewCell子类,如何绘制按钮?

ios - 将数字 0 - 59 添加到 NSMutableArray 以显示在 pickerView 中

iphone - 将用户从 iOS 应用程序登录到远程 API 的正确流程

ios - 使用 NSMutableArray 创建 .csv 文件时文本换行

perl - 将 Perl 中的哈希解析为 CSV 格式

ios - 将坐标从十进制度数转换为可能的 EPSG 4326

ios - 调整 View 的大小使其他 View 在 UITableViewCell 中反弹

ios - swift 设计模式。为什么他们包括 Any, AnyObject

python - 从 CSV 为 Google map 创建 KML 文件

python - BeautifulSoup 和 CSV : Delimiter after every Character