create csv or xls file

Hi,


I am totally new to XCode and swift. I would really appreciate if anyone could tell me how to create a csv or xls file using swift. Thank you very much.


Emma

Replies

XLS files are complex so I’m going to ignore that.

CSV files are a lot less complex—although more complex than most folks think—so I’ll focus there. Here’s some simplifying assumptions:

  • you’re build an iOS or Mac app, and thus have access to Foundation

  • the data will be small enough to fit in memory easily

  • the text encoding will be UTF-8

  • the line breaks will be Windows style (CR LF)

  • the items won’t include any weird characters (like CR or LF)

Based on those requirements, here’s an implementation that optimised for readability:

import Foundation

func quoteColumn(column: String) -> String {
    if column.containsString(",") || column.containsString("\"") {
        return "\"" + column.stringByReplacingOccurrencesOfString("\"", withString: "\"\"") + "\""
    } else {
        return column
    }
}

func commaSeparatedValueStringForColumns(columns: [String]) -> String {
    return columns.map {column in
        quoteColumn(column)
    }.joinWithSeparator(",")
}

func commaSeparatedValueDataForLines(lines: [[String]]) -> NSData {
    return lines.map { column in
        commaSeparatedValueStringForColumns(column)
    }.joinWithSeparator("\r\n").dataUsingEncoding(NSUTF8StringEncoding)!
}

let input = [
    ["l1,c1", "Quinn \"The Eskimo!\", DTS Engineer", "l1c3"],
    ["l2c1", "l2c2", "l2c3"]
]
print(commaSeparatedValueDataForLines(input))

Or if you want something more compact:

func CSVDataForLines(input: [[String]]) -> NSData {
    return input.map {
        $0.map {
            $0.containsString(",") || $0.containsString("\"")
            ? "\"" + $0.stringByReplacingOccurrencesOfString("\"", withString: "\"\"") + "\""
            : $0
        }.joinWithSeparator(",")
    }.joinWithSeparator("\r\n").dataUsingEncoding(NSUTF8StringEncoding)!
}

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"