2015-09-15 19 views
8

我想導出一個cvs文件。我如何精確地從iOS寫出一個從iOS寫入的CSV文件?

用下面的代碼我設法獲取文件

let fileName = "sample.csv"//"sample.txt"   
    @IBAction func createFile(sender: AnyObject) { 
      let path = tmpDir.stringByAppendingPathComponent(fileName) 
      let contentsOfFile = "No,President Name,Wikipedia URL,Took office,Left office,Party,Home State\n1,George Washington,http://en.wikipedia.org/wiki/George_Washington,30/04/1789,4/03/1797,Independent,Virginia\n2,John Adams,http://en.wikipedia.org/wiki/John_Adams,4/03/1797,4/03/1801,Federalist,Massachusetts\n3,Thomas Jefferson,http://en.wikipedia.org/wiki/Thomas_Jefferson,4/03/1801,4/03/1809,Democratic-Republican,Virginia\n4,James Madison,http://en.wikipedia.org/wiki/James_Madison,4/03/1809,4/03/1817,Democratic-Republican,Virginia\n5,James Monroe,http://en.wikipedia.org/wiki/James_Monroe,4/03/1817,4/03/1825,Democratic-Republican,Virginia\n6,John Quincy Adams,http://en.wikipedia.org/wiki/John_Quincy_Adams,4/03/1825,4/03/1829,Democratic-Republican/National Republican,Massachusetts" 
       //"Sample Text repacement for future cvs data"content to save 

      // Write File 

      do { 
       try contentsOfFile.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding) 
       print("File sample.txt created at tmp directory") 
      } catch { 

       print("Failed to create file") 
       print("\(error)") 
      } 

     } 

// Share button 
    @IBAction func shareDoc(sender: AnyObject) { 
     print("test share file") 

     docController.UTI = "public.comma-separated-values-text" 
      docController.delegate = self//delegate 
      docController.name = "Export Data" 
      docController.presentOptionsMenuFromBarButtonItem(sender as! UIBarButtonItem, animated: true) 

     //} 
    } 

當我點擊模擬器我看到下面的共享文件按鈕:

enter image description here

,並與快看它顯示

enter image description here

所以接下來我做的就是用我的iphone 5進行測試,我試着發郵件給sample.csv,但我只收到郵件正文而不是csv文件?

  1. 我該如何實際發送電子郵件的.csv文件?
  2. 哪些出口可能性在那裏?
+0

任何人任何想法? – alex

回答

18

爲了通過電子郵件發送.csv文件,你可以做到以下幾點:

  1. 此導入添加到類的頂部。它允許您使用MFMailComposeViewController,這是一種發送電子郵件的方式。

    import MessageUI 
    
  2. 生成你的數據,我做了一個樣本:

    // Creating a string. 
    var mailString = NSMutableString() 
    mailString.appendString("Column A, Column B\n") 
    mailString.appendString("Row 1 Column A, Row 1 Column B\n") 
    mailString.appendString("Row 2 Column A, Row 2 Column B\n") 
    
    // Converting it to NSData. 
    let data = mailString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) 
    
    // Unwrapping the optional. 
    if let content = data {   
        print("NSData: \(content)") 
    } 
    
  3. 生成MFMailComposeViewController

    // Generating the email controller. 
        func configuredMailComposeViewController() -> MFMailComposeViewController { 
         let emailController = MFMailComposeViewController() 
         emailController.mailComposeDelegate = self 
         emailController.setSubject("CSV File") 
         emailController.setMessageBody("", isHTML: false) 
    
         // Attaching the .CSV file to the email. 
         emailController.addAttachmentData(data!, mimeType: "text/csv", fileName: "Sample.csv") 
    
         return emailController 
        } 
    
    // If the view controller can send the email. 
    // This will show an email-style popup that allows you to enter 
    // Who to send the email to, the subject, the cc's and the message. 
    // As the .CSV is already attached, you can simply add an email 
    // and press send. 
        let emailViewController = configuredMailComposeViewController() 
        if MFMailComposeViewController.canSendMail() { 
         self.presentViewController(emailViewController, animated: true, completion: nil) 
        } 
    

在你的情況,因爲你已經創建了文件,您可以直接通過更改CSV附加到的行來附加該文件郵件:

emailController.addAttachmentData(NSData(contentsOfFile: "YourFile")!, mimeType: "text/csv", fileName: "Sample.csv") 

回答依據:Attach csv to email xcodeCreate CSV file in Swift and write to file

8

斯威夫特3

class ViewController: UIViewController { 

var taskArr = [Task]() 
var task: Task! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    task = Task() 
    for _ in 0..<5 { 
     task.name = "Raj" 
     task.date = "\(Date())" 
     task.startTime = "Start \(Date())" 
     task.endTime = "End \(Date())" 
     taskArr.append(task!) 
    } 

    creatCSV() 
} 

// MARK: CSV file creating 
    func creatCSV() -> Void { 
     let fileName = "Tasks.csv" 
     let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName) 
     var csvText = "Date,Task Name,Time Started,Time Ended\n" 

     for task in taskArr { 
      let newLine = "\(task.date),\(task.name),\(task.startTime),\(task.endTime)\n" 
      csvText.append(newLine) 
     } 

     do { 
      try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8) 
     } catch { 
      print("Failed to create file") 
      print("\(error)") 
     } 
     print(path ?? "not found") 
    } 
} 

任務模型類

創建CSV文件
class Task: NSObject { 
    var date: String = "" 
    var name: String = "" 
    var startTime: String = "" 
    var endTime: String = "" 
} 

CSV輸出顯示如下格式

enter image description here

+0

可以設置一個文本來對齊中心嗎? –

+0

我沒有找到關於csv文件的文本對齊的任何解決方案。 –

+0

我們如何做到這一點在迅捷4? – Antony