我如何从 swift 编写的 iOS 中准确导出 csv 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32593516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:39:29  来源:igfitidea点击:

How do i exactly export a csv file from iOS written in swift?

iosswiftcsvexport

提问by alex

I am trying to export an cvs file.

我正在尝试导出一个 cvs 文件。

With the following code i manage to get the file

使用以下代码我设法获取文件

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)

        //}
    }

When i click the share file button in the simulator i see the following:

当我单击模拟器中的共享文件按钮时,我看到以下内容:

enter image description here

在此处输入图片说明

and with quick look it shows

并快速查看它显示

enter image description here

在此处输入图片说明

So the next thing i did was testing with my iphone 5 and i tried to email sample.csv but i am only getting the message body and not the csv file???

所以接下来我做的是用我的 iphone 5 进行测试,我尝试通过电子邮件发送 sample.csv 但我只收到邮件正文而不是 csv 文件???

  1. how can i actually email the .csv file?
  2. which export possibilities are there?
  1. 我怎样才能真正通过电子邮件发送 .csv 文件?
  2. 有哪些出口可能性?

回答by Lucas

In order to email the .csv file, you can do the following:

要通过电子邮件发送 .csv 文件,您可以执行以下操作:

  1. Add this import to the top of the class. It allows you to use MFMailComposeViewController, which is a way to send emails.

    import MessageUI
    
  2. Generate your data, a sample I have done is:

    // 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. Generate the 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)
        }
    
  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)
        }
    

In your case, as you have already created the file, you can simply attach that directly by changing the line where the CSV is attached to the mail for:

在您的情况下,由于您已经创建了文件,您可以通过更改将 CSV 附加到邮件的行直接附加该文件:

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

Answer based on: Attach csv to email xcode, Create CSV file in Swift and write to file

答案基于:将 csv 附加到电子邮件 xcode在 Swift 中创建 CSV 文件并写入文件

回答by Raj Joshi

Creating CSV file in Swift

在 Swift 中创建 CSV 文件

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")
    }
}

Task Model class

任务模型类

class Task: NSObject {
    var date: String = ""
    var name: String = ""
    var startTime: String = ""
    var endTime: String = ""
}

CSV output show as below format

CSV 输出显示如下格式

enter image description here

在此处输入图片说明

回答by swift2geek

Swift 5.0.1, Xcode 10.2.1 version

Swift 5.0.1, Xcode 10.2.1 版本

    private func injectExportButton() {
    var csvIcon: UIImage
    switch self.theme {
    case .dark:
        csvIcon = UIImage(named: "csv-export.dark", in: Bundle.framework)!
    case .light:
        csvIcon = UIImage(named: "csv-export.light", in: Bundle.framework)!
    }
            let imgWidth = csvIcon.size.width
            let imgHeight = csvIcon.size.height
            let button: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: imgWidth, height: imgHeight))
            button.setBackgroundImage(csvIcon, for: UIControl.State())
            button.alpha = 0
    button.addTarget(self, action: #selector(csvExportButtonClicked), for: .touchUpInside)
            UIView.animate(withDuration: 0.5) {
                button.alpha = 1
            }
            navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

}

@objc private func csvExportButtonClicked() {
    debugPrint("export clicked")
    createCSV()
}

private func createCSV() -> Void {
    let fileName = getDocumentsDirectory().appendingPathComponent("OutputD.csv")
    var csvOutputText = "Result, Date, Name\n"
    history.results.forEach { result in
        let newLine = "\(String(describing: result.value)),\(String(describing: result.date)),\(String(describing: result.name))\n"
        csvOutputText.append(newLine)
    }
    do {
        try csvOutputText.write(to: fileName, atomically: true, encoding: String.Encoding.utf8)
    } catch {
        print("Failed to create file")
        print("\(error)")
    }
    let activity = UIActivityViewController(activityItems: ["your results", fileName], applicationActivities: nil)
    present(activity, animated: true)
}

private func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

回答by John Ro

SWIFT 5

快速 5

func creatCSV() {
    let fileName = "exportar_serv.csv"

    /* CREAR UN ARCHIVO NUEVO EN EL DIRECTORIO PRINCIPAL */
    guard let path = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(fileName) as NSURL else {
        return }

    var csvText = "id,name,imageName\n"

    for task in taskArr {
        let x : Int64 = task.id!
        let id2 = String(x)

        let newLine = "\(id2),\(task.name),\(task.imageName)\n"
        csvText.append(newLine)
    } // for

    do {
        try csvText.write(to: path as URL, atomically: true, encoding: String.Encoding.utf8)
        print("DATOS GUARDADOS")
    } catch {
        print("Failed to create file")
        print("\(error)")
    } // catch

} // CreateCSV