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

I am creating an application with master data (1 object with 5 attributes) that are displayed in a tableView. Now I would like to export this data to a CSV file (so that I can send this file using mail from my phone), so I can open it in excel on windows. I searched a lot, but did not find the right answer. Can someone help me or give me a link to a good explanation or tutorial?

I'm building fast.

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) } } 
+6
source share
1 answer

This is a short way to do whatever you want - you pass in an array of managed objects and a string that is the name of the CSV file. The method writes the CSV to a file. I believe that you already have most of this code, what is missing is the last two lines, which simply write the line to a new file in the 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 } 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 } 

Now, somewhere else in the code, you need to create an NSData from this line and add it to the 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 make the usual material with the composer (set the body, theme, etc.) and present it to the user!

EDIT:

Edited the answer to better answer the question.

+6
source

All Articles