我如何从用swift编写的iOS中完全导出csv文件?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何从用swift编写的iOS中完全导出csv文件?相关的知识,希望对你有一定的参考价值。

我想导出一个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
1,George Washington,http://en.wikipedia.org/wiki/George_Washington,30/04/1789,4/03/1797,Independent,Virginia
2,John Adams,http://en.wikipedia.org/wiki/John_Adams,4/03/1797,4/03/1801,Federalist,Massachusetts
3,Thomas Jefferson,http://en.wikipedia.org/wiki/Thomas_Jefferson,4/03/1801,4/03/1809,Democratic-Republican,Virginia
4,James Madison,http://en.wikipedia.org/wiki/James_Madison,4/03/1809,4/03/1817,Democratic-Republican,Virginia
5,James Monroe,http://en.wikipedia.org/wiki/James_Monroe,4/03/1817,4/03/1825,Democratic-Republican,Virginia
6,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. 有哪些出口可能性?
答案

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

  1. 将此导入添加到类的顶部。它允许您使用MFMailComposeViewController,这是一种发送电子邮件的方式。 import MessageUI
  2. 生成您的数据,我所做的一个示例是: // Creating a string. var mailString = NSMutableString() mailString.appendString("Column A, Column B ") mailString.appendString("Row 1 Column A, Row 1 Column B ") mailString.appendString("Row 2 Column A, Row 2 Column B ") // 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

另一答案

在Swift 3中创建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
"

        for task in taskArr {
            let newLine = "(task.date),(task.name),(task.startTime),(task.endTime)
"
            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")
    }
}

任务模型类

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

CSV输出显示如下格式

enter image description here

以上是关于我如何从用swift编写的iOS中完全导出csv文件?的主要内容,如果未能解决你的问题,请参考以下文章

如何从用 Swift 编写的 Flutter 平台特定代码启动 ViewController?

如何在 iOS 中使用 Swift/SwiftUI 将我从应用数据导出的文本文件移动到应用沙箱之外的位置?

将文本表的数据导出为 .csv (Tableau)

导出为 csv 完全适合第一个单元格

如何从用 C# 编写的抽象基类继承

我应该如何从用 PHP 编写的 RESTful api 提供二进制文件(图像/音频)?