/CSVParser

A swift package for read and write CSV file

Primary LanguageSwiftMIT LicenseMIT

CSVParser

A swift library for fast read and write CSV file. This library supports all Apple platform and Linux.

Build Status Carthage compatible Plafrom

List to do


  • get column by string subscript
  • error
  • initialization from string
  • Convert JSON To CSV
  • Convert CSV To JSON

Requirements


  • Swift 3.0+

Installation


Swift Package Manager(Support Ubuntu)

If you want to use this package on Ubuntu, you shounld install with Swift Package Manager

In Package.swift file

import PackageDescription

let package = Package(
  name: "YourProject",
  dependencies: [
    .Package(url: "https://github.com/Nero5023/CSVParser",
        majorVersion: 1),
    ]
)

Run command

$ swift build

Carthage

To integrate CSVParser into your Xcode project using Carthage, specify it in your Cartfile:

github "Nero5023/CSVParser" ~> 1.1.5

Run carthage update to build the framework and drag the built CSVParser.framework into your Xcode project.

Usage

Initialization

let csv = try CSVParser(filePath: "path/to/csvfile")

//catch error
do {
	let csv = try CSVParser(filePath: "path/to/csvfile")
}catch {
	// Error handing
}

// Custom delimiter
do {
	let csv = try CSVParser(filePath: "path/to/csvfile", delimiter: ";")
}catch {
	// Error handing
}

// init from elements
let csv = try CSVParser(elements: [["a", "b", "c"], ["1", "2", "3"]])

Read data

do {
	let csv = try CSVParser(filePath: "path/to/csvfile")
	// get every row in csv
	for row in csv {
        print(row) // ["first column", "sceond column", "third column"]
    }
    
    // get row by int subscript 
    csv[10] // the No.10 row
    
    // get column by string subscript
    csv["id"] // column with header key "id" 
	
}catch {
	// Error handing
}

Write data

do {
	let csv = try CSVParser(filePath: "path/to/csvfile")
	// get every row in csv
	csv[0] = ["test0", "test1", "test2"]
	csv.wirite(toFilePath: "path/to/destination/file")
	
}catch {
	// Error handing
}

Subscript

// get row by int subscript 
csv[10] // the No.10 row
    
// get column by string subscript
csv["id"] // column with header key "id" 

Get dictionary elements

for dic in csv.enumeratedWithDic() {
	print(dic) // dic is [String: String]	
}

CSV to JSON

The result json type is [{"header0": "a","header1": "b"},{"header0": "a", "header1": "b"}]

do {
	let jsonStr = try csv.toJSON()
}catch {
	// Error handing
} 

JSON to CSV string

Now only support this json type [{"header0": "a","header1": "b"},{"header0": "a", "header1": "b"}]

do {
	let csvString = try CSVParser.jsonToCSVString(jsonData: jsonData) // jsonData is the Data type ot json
}catch {
	// Error handing
}