CSV.swift用 Swift 编写的 CSV 读写库

联合创作 · 2023-10-02 04:28

CSV.swift 是用 Swift 编写的 CSV 读写库。

读取 CSV 的用法

从字符串

import CSV

let csvString = "1,foo\n2,bar"
let csv = try! CSVReader(string: csvString)
while let row = csv.next() {
    print("\(row)")
}
// => ["1", "foo"]
// => ["2", "bar"]

从文件

注意:默认字符编码是UTF8.

import Foundation
import CSV

let stream = InputStream(fileAtPath: "/path/to/file.csv")!
let csv = try! CSVReader(stream: stream)
while let row = csv.next() {
    print("\(row)")
}

获取 Header 行

import CSV

let csvString = "id,name\n1,foo\n2,bar"
let csv = try! CSVReader(string: csvString,
                         hasHeaderRow: true) // It must be true.

let headerRow = csv.headerRow!
print("\(headerRow)") // => ["id", "name"]

while let row = csv.next() {
    print("\(row)")
}
// => ["1", "foo"]
// => ["2", "bar"]

使用下标获取字段值

import CSV

let csvString = "id,name\n1,foo"
let csv = try! CSVReader(string: csvString,
                         hasHeaderRow: true) // It must be true.

while csv.next() != nil {
    print("\(csv["id"]!)")   // => "1"
    print("\(csv["name"]!)") // => "foo"
}

提供字符编码

如果使用文件路径,则可以向初始化程序提供字符编码。

import Foundation
import CSV

let stream = InputStream(fileAtPath: "/path/to/file.csv")!
let csv = try! CSVReader(stream: stream,
                         codecType: UTF16.self,
                         endian: .big)

将一行读入 Decodable 对象

如果你有一个符合Decodable协议的目标对象,那就可以使用该对象的新实例序列化一行。

struct DecodableExample: Decodable {
    let intKey: Int
    let stringKey: String
    let optionalStringKey: String?
}

let csv = """
    intKey,stringKey,optionalStringKey
    1234,abcd,
    """

var records = [DecodableExample]()
do {
    let reader = try CSVReader(string: csv, hasHeaderRow: true)
    let decoder = CSVRowDecoder()
    while reader.next() != nil {
        let row = try decoder.decode(DecodableExample.self, from: reader)
        records.append(row)
    }
} catch {
    // Invalid row format
}

写入 CSV 的用法

写入内存并获取 CSV 字符串

注意:默认字符编码是UTF8.

import Foundation
import CSV

let csv = try! CSVWriter(stream: .toMemory())

// Write a row
try! csv.write(row: ["id", "name"])

// Write fields separately
csv.beginNewRow()
try! csv.write(field: "1")
try! csv.write(field: "foo")
csv.beginNewRow()
try! csv.write(field: "2")
try! csv.write(field: "bar")

csv.stream.close()

// Get a String
let csvData = csv.stream.property(forKey: .dataWrittenToMemoryStreamKey) as! Data
let csvString = String(data: csvData, encoding: .utf8)!
print(csvString)
// => "id,name\n1,foo\n2,bar"

写入文件

注意:默认字符编码是UTF8.

import Foundation
import CSV

let stream = OutputStream(toFileAtPath: "/path/to/file.csv", append: false)!
let csv = try! CSVWriter(stream: stream)

try! csv.write(row: ["id", "name"])
try! csv.write(row: ["1", "foo"])
try! csv.write(row: ["1", "bar"])

csv.stream.close()

安装

CocoaPods

pod  'CSV.swift' ,  '~> 2.4.3'

Carthage

github "yaslab/CSV.swift" ~> 2.4.3 

Swift 包管理器

.package(url: "https://github.com/yaslab/CSV.swift.git", .upToNextMinor(from: "2.4.3"))

 

 

浏览 1
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报