title: How to create a CSV file from Core Data (swift)
body: <p>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?  </p>
  
  <p>I'm  building in swift btw.  </p>
  
  <pre><code>func createExportString() -&gt; 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)
      }
  }
  </code></pre>