Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a CSV file from Core Data (swift)

I'm building an app with core data (1 entity with 5 attributes) that display in a tableView. Now i would like to export this data to a CSV file (so i can send this file with mail from phone) so i can open it in excel on a windows. i search a lot but didn't find the right answer. Can someone help me or give me a link to a good explanation or tutorial?

I'm building in swift btw.

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)
    }
}
like image 538
adams.s Avatar asked Feb 20 '16 23:02

adams.s


1 Answers

This is a concise way of doing all you want - you pass array of managed objects and a string that is CSV's filename. The method writes your CSV to a file. I believe you already have most of this in your code, the thing that is lacking are last two lines that just write a string into a new file in "Documents" directory.

func writeCoreDataObjectToCSV(objects: [NSManagedObject], named: String) -> String? {
    /* We assume that all objects are of the same type */
    guard objects.count > 0 else {
        return nil
    }
    let firstObject = objects[0]
    let attribs = Array<Any>(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
}

Now, somewhere else in the code you need to create NSData from this string and add it to mail composer:

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

Then, do the usual stuff with the composer (set body, topic, etc) and present it to the user!

EDIT:

Edited the answer to better answer the question.

like image 100
Terminus Avatar answered Nov 14 '22 22:11

Terminus