【问题标题】:Swift: Export strings to CSV with cell line breaksSwift:使用单元格换行符将字符串导出到 CSV
【发布时间】:2019-09-02 04:46:14
【问题描述】:

我需要以 CSV 格式导出一些字符串。一切正常,但我无法在单元格中设置换行符。 \t\n\r 不适合,因为它只是将文本换行。

func export() {

    let fileName = "Test.csv"
    let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

    var csvText = "Date,1,2,3\n"

    if history.count != 0 {

        var all = ""
        let date = "24.08.2019"
        let x1 = "[10:40]: ????\n"
        all.append(x1)
        let x2 = "[10:40]: ????\r"
        all+=x2
        let x3 = "[10:40]: ????\r"
        all+=x3
        let s2 = ""
        let s3 = ""

        let newLine = "\(currentDay),\(all),\(s2),\(s3)\n"

        csvText.append(contentsOf: newLine)

        do {
            try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)

            let vc = UIActivityViewController(activityItems: [path!], applicationActivities: [])
            vc.excludedActivityTypes = [
                UIActivity.ActivityType.assignToContact,
                UIActivity.ActivityType.saveToCameraRoll,
                UIActivity.ActivityType.postToFlickr,
                UIActivity.ActivityType.postToVimeo,
                UIActivity.ActivityType.postToTencentWeibo,
                UIActivity.ActivityType.postToTwitter,
                UIActivity.ActivityType.postToFacebook,
                UIActivity.ActivityType.openInIBooks
            ]

            present(vc, animated: true, completion: nil)

        } catch {

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

    } else {

        print("## Error")
    }

}

输出: Image

有没有人知道在单元格中达到换行符的其他解决方案(如下图所示)?

【问题讨论】:

  • 将单元格值放在双引号中。

标签: swift string csv export-to-csv


【解决方案1】:

如何创建 CSV 取决于 CSV 阅读器如何读取它。

但通常的 CSV 阅读器接受这种转义:

extension String {
    var csvEscaped: String {
        struct My {
            static let specials = CharacterSet(charactersIn: ", \r\n\t\"")
        }
        return self.unicodeScalars.contains{My.specials.contains($0)}
            ? "\"" + self.replacingOccurrences(of: "\"", with: "\"\"") + "\""
            : self
    }
}

并像这样使用它:

let newLine = "\(date.csvEscaped),\(all.csvEscaped),\(s2.csvEscaped),\(s3.csvEscaped)\n"

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多