如何从Core Data创建CSV文件(swift)

时间:2016-02-20 23:46:33

标签: ios swift csv core-data

我正在使用在tableView中显示的核心数据(具有5个属性的1个实体)构建应用程序。现在我想将这些数据导出到CSV文件(所以我可以通过电话发送此文件),这样我就可以在windows上的excel中打开它。我搜索了很多,但没有找到正确的答案。有人可以帮助我或给我一个良好的解释或教程的链接?

我快速建造。

func createExportString() -> String {
    var merk: String?
    var ref: String?
    var beschrijving: String?
    var aantal: String?
    var wbs: String?

    var export = NSLocalizedString("merk, ref, beschrijving, aantal, wbs \n", comment: "")
            merk = Lijst.valueForKey("merk") as? String
            ref = Lijst.valueForKey("ref") as? String
            aantal = Lijst.valueForKey("aantal") as? String
            beschrijving = Lijst.valueForKey("beschrijving") as? String
            wbs = Lijst.valueForKey("wbs") as? String


            let merkString = "\(merk!)" ?? "-"
            let refString = "\(ref!)" ?? "-"
            let beschString = "\(beschrijving!)" ?? "-"
            let aantalString = "\(aantal!)" ?? "-"
            let wbsString = "\(wbs!)" ?? "-"

            export += merkString + "," + refString + "," + beschString + "," + aantalString +
                "," + wbsString + "\n"

    print("This is what the app will export: \(export)")
    return export
}

@IBAction func saveToCSV(sender: AnyObject) {
    exportDatabase()
}

func exportDatabase() {
    var exportString = createExportString()
    saveAndExport(exportString)
}

func saveAndExport(exportString: String) {
    let exportFilePath = NSTemporaryDirectory() + "export.csv"
    let exportFileURL = NSURL(fileURLWithPath: exportFilePath)
    NSFileManager.defaultManager().createFileAtPath(exportFilePath, contents: NSData(), attributes: nil)
    var fileHandleError: NSError? = nil
    var fileHandle: NSFileHandle? = nil
    do {
        fileHandle = try NSFileHandle(forWritingToURL: exportFileURL)
    } catch {
        print( "Error with fileHandle")
    }

    if fileHandle != nil {
        fileHandle!.seekToEndOfFile()
        let csvData = exportString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        fileHandle!.writeData(csvData!)

        fileHandle!.closeFile()

        let firstActivityItem = NSURL(fileURLWithPath: exportFilePath)
        let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [firstActivityItem], applicationActivities: nil)

        self.presentViewController(activityViewController, animated: true, completion: nil)
    }
}

1 个答案:

答案 0 :(得分:7)

这是完成所有操作的简洁方法 - 您传递托管对象数组和CSV文件名字符串。该方法将CSV写入文件。我相信你已经在你的代码中已经有了大部分内容,缺少的是最后两行,只是将字符串写入“Documents”目录中的新文件。

func writeCoreDataObjectToCSV(objects: [NSManagedObject], named: String) -> String {
    /* We assume that all objects are of the same type */
    guard objects.count > 0 else {
        return
    }
    let firstObject = objects[0]
    let attribs = Array(firstObject.entity.attributesByName.keys)
    let csvHeaderString = (attribs.reduce("",combine: {($0 as String) + "," + $1 }) as NSString).substringFromIndex(1) + "\n"

    let csvArray = objects.map({object in
        (attribs.map({(object.valueForKey($0) ?? "NIL").description}).reduce("",combine: {$0 + "," + $1}) as NSString).substringFromIndex(1) + "\n"
    })
    let csvString = csvArray.reduce("", combine: +)

    return csvHeaderString+csvString
}

现在,您需要在代码中的其他位置从此字符串创建NSData并将其添加到邮件编辑器中:

let csvString = .....
let data = csvString.dataUsingEncoding(NSUTF8StringEncoding)
let composer = MFMailComposeViewController()
composer.addAttachmentData(attachment: data,
          mimeType mimeType: "text/csv",
          fileName filename: "mydata.csv")

然后,用作曲家(设置正文,主题等)做常用的东西并将其呈现给用户!

编辑:

编辑答案以更好地回答这个问题。