CSVParser - A swift library for fast read and write CSV file

Related tags

CSV swift csv-parser
Overview

CSVParser

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

Carthage compatible Plafrom

List to do


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

Requirements


  • Swift 4.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:

2.0.0 ">
github "Nero5023/CSVParser" ~> 2.0.0

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
} 
Comments
  • ";" delimiter... crash ?

    Hi !

    So, excel being excel, it exports utf-8 csv using semi-columns (;) characters as delimiters, and \r as line separators.

    So I specified those as such... and running crashes the program in Xcode, hitting a breakpoint in the CFHash thread, before stopping with

    Message from debugger: Terminated due to signal 9

    I don't have any breakpoint in my code, and CSVParser is the only framework I'm using. Any idea ?

    Just in case, here's my function

        func importCSV(filePath: String) {
    	do {
    		let delimeter: Character = ";"
    		let lineSeparator: Character = "\r"
    		let csv = try CSVParser(filePath: filePath, delimiter: delimeter, lineSeparator: lineSeparator)
    		var i = 0
    		for row in csv {
    			print("Row \(i): \(row)\n") // ["first column", "sceond column", "third column"]
    			i += 1
    		}
    		do {
    			let jsonStr = try csv.toJSON()
    			consoleIO.writeMessage("json: \(jsonStr)")
    		} catch let csvToJsonError {
    			consoleIO.writeMessage(csvToJsonError.localizedDescription, to: .error)
    		}
    	} catch let error {
    		print(error)
    		consoleIO.writeMessage(error.localizedDescription, to: .error)
    	}
        }
    

    Using a random character as delimiter (such as "j") makes it work just fine... almost.

    csv.toJSON() fails on the enumeratedWithDic() function, but I guess it's because there aren't any headers (since "j" isn't really a delimiter in the csv file ^^")

    opened by El-Fitz 3
  • Can't form a Character from an empty String

    Can't form a Character from an empty String

    Hi there!

    I'm trying to initialize a CSVParser from a String and I'm getting a fatal error.

    Line 29 of parser.swift is if inputContents[cursor] == quotes {

    This line is throwing fatal error: Can't form a Character from an empty String

    inputContents[cursor] and quotes are both equal to a single " and I've tried several things trying to debug this but got nowhere.

    This is the string I'm passing to the initializer with let csvParser = try CSVParser(content: csvString) is:

    "Subject 1 #hashtagone","http://example.com/one"
    "Subject 2 #hashtagtwo","http://example.com/two"
    "Subject 3 #hashtagthree","http://example.com/three"
    

    Any ideas?

    opened by codesman 2
  • Headers property?

    Headers property?

    It would be nice to be able to have headers parsed separately from rows(if the file has headers) so you could do something like let csv = CSVParser(content: string, hasHeaders: true) and then be able to let headers = csv.headers and let rows = csv.rows

    opened by codesman 1
  • Restrict APIs to those allowed in app extensions

    Restrict APIs to those allowed in app extensions

    This turns on the build option to restrict API usage to only APIs allow in app extensions. This setting is on the "General" tab of the build settings for each of the CSVParser and CSVParseriOS targets in the project.

    Turning this on allows the framework to be included in app extensions on both macOS and iOS.

    image

    opened by bradsokol 0
  • Cannot assign through subscript: subscript is get-only after swift 4.1

    Cannot assign through subscript: subscript is get-only after swift 4.1

    When i try to Write data

    let csv = try CSVParser(filePath: "path/to/csvfile")
    // get every row in csv
    
        below line throws an error after updating to 4.1
    csv[0] = ["test0", "test1", "test2"]  //  **Cannot assign through subscript: subscript is get-only**
    
    csv.wirite(toFilePath: "path/to/destination/file")
    
    opened by iNarendra 0
  • Unable to install onto actual iPhone

    Unable to install onto actual iPhone

    Whenever one of my project is run with CSVParser as one of its frameworks (and even when it is the only framework used in the entire project), and run on an actual iPhone, the error "This Application's bundle identifier does not match its code signing identifier". Are there any solutions to this problem by anyone?

    opened by peironggg 0
  • Not able to build on last xcode, swift 4.1

    Not able to build on last xcode, swift 4.1

    extension CSVParser: RangeReplaceableCollection {
      public func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C : Collection, C.Iterator.Element == Array<String> {
        self._rows.replaceSubrange(subrange, with: newElements)
      }
      public func reserveCapacity(_ n: Int) {
        self._rows.reserveCapacity(n)
      }
    }
    

    Here i have got error.

    opened by KanybekMomukeyev 5
  • Crash on Linux

    Crash on Linux

    I got an error when running an app on Ubuntu.

    Fatal error: init(contentsOfFile:usedEncoding:) is not yet implemented: file Foundation/NSString.swift, line 1308
    

    It's caused by this line

    public convenience init(filePath: String, delimiter: Character = ",", lineSeparator: Character = "\n") throws {
        let fileContent = try String(contentsOfFile: filePath) // <-- this line
        try self.init(content: fileContent, delimiter: delimiter, lineSeparator: lineSeparator)
      }
    

    You should consider to use the same method with explicit encoding. Following code works well on Ubuntu:

    let fileContent = try String(contentsOfFile: filePath, encoding: .utf8)
    
    opened by honghaoz 0
  • Russian Excel problem in encoding

    Russian Excel problem in encoding

    Hi, thanks for great library! Have some issues:

    (1) I have some problems in text encoding in Russian excel file, what can cause this issue? (2) Also, it would be best to write some performance test, because in large files it's working slowly.

    img_2017-03-13 12 23 10

    opened by KanybekMomukeyev 2
Owner
Nero
Nero
CSV reading and writing library written in Swift.

CSV.swift CSV reading and writing library written in Swift. Usage for reading CSV From string import CSV let csvString = "1,foo\n2,bar" let csv = try

Yasuhiro Hatta 594 Dec 29, 2022
A csv parser written in swift conforming to rfc4180

CSwiftV A csv parser conforming (and tested as much) to rfc4180 i.e the closest thing to a csv spec. It is currently all in memory so not suitable for

Daniel Haight 166 Dec 13, 2022
CodableCSV - Read and write CSV files row-by-row or through Swift's Codable interface.

CodableCSV provides: Imperative CSV reader/writer. Declarative CSV encoder/decoder. Support multiple inputs/outputs: Strings, Data blobs, URLs, and St

Marcos Sánchez-Dehesa 369 Jan 8, 2023
Taking a string containing a csv file and split it into records (aka lines) containing fields of data (aka Array of SubStrings)

Swift .csv parser Taking a string containing a csv file and split it into records (aka lines) containing fields of data (aka Array of SubStrings). Par

Matthias 0 Dec 29, 2021
A command line tool to parse pricing from a pdf and generate an updated csv file for House Call Pro

A command line tool to parse pricing from a pdf and generate an updated csv file for House Call Pro

hhe-dev 10 Feb 17, 2022
Capacitor File Opener. The plugin is able to open a file given the mimeType and the file uri

Capacitor File Opener. The plugin is able to open a file given the mimeType and the file uri. This plugin is similar to cordova-plugin-file-opener2 without installation support.

Capacitor Community 32 Dec 21, 2022
Easy to read and write chainable animations in Objective-C and Swift

Whats new in version 3.x? Swiftier syntax Swift 4 support Bug fixes and improvements Whats new in version 2.x? Re-architected from the ground up, no m

Jeff Hurray 3.2k Dec 30, 2022
⛓ Easy to Read and Write Multi-chain Animations Lib in Objective-C and Swift.

中文介绍 This project is inspired by JHChainableAnimations! Why Choose LSAnimator & CoreAnimator? You can write complex and easy-to-maintain animations in

木子 1.6k Nov 22, 2022
Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types

Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types

Mathias Quintero 9 Sep 25, 2022
📝 Read, update and write your Xcode projects

XcodeProj XcodeProj is a library written in Swift for parsing and working with Xcode projects. It's heavily inspired by CocoaPods XcodeProj and xcode.

Tuist 1.7k Dec 28, 2022
Write amazing, strong-typed and easy-to-read NSPredicate.

PredicateFlow Write amazing, strong-typed and easy-to-read NSPredicate. This library allows you to write flowable NSPredicate, without guessing attrib

Andrea Del Fante 103 Aug 12, 2022
Write amazing, strong-typed and easy-to-read NSPredicate.

PredicateFlow Write amazing, strong-typed and easy-to-read NSPredicate. This library allows you to write flowable NSPredicate, without guessing attrib

Andrea Del Fante 103 Aug 12, 2022
Blocks Based Bluetooth LE Connectivity framework for iOS/watchOS/tvOS/OSX. Quickly configure centrals & peripherals, perform read/write operations, and respond characteristic updates.

ExtendaBLE Introduction ExtendaBLE provides a very flexible syntax for defining centrals and peripherals with ease. Following a blocks based builder a

Anton 94 Nov 29, 2022
ReadWriteLock - Swift Implementation of a standard Read/Write lock.

ReadWriteLock A Swift implementation of a Read/Write lock. I'm really amazed that the Swift Standard Library (nor the Objective-C standard library) ha

Galen Rhodes 1 Mar 1, 2022
Phiole - Allow to write or read from standards stream or files for script or CLI application

No longer maintained! Phiole - Φole Simple object to wrap three NSFileHandle: 'output', 'error' to write and 'input' to read There is of course a defa

Eric Marchand 8 Sep 10, 2018
CSV reading and writing library written in Swift.

CSV.swift CSV reading and writing library written in Swift. Usage for reading CSV From string import CSV let csvString = "1,foo\n2,bar" let csv = try

Yasuhiro Hatta 594 Dec 29, 2022
TTextField is developed to help developers can initiate a fully standard textfield including title, placeholder and error message in fast and convinient way without having to write many lines of codes

TTextField is developed to help developers can initiate a fully standard textfield including title, placeholder and error message in fast and convinient way without having to write many lines of codes

Nguyen Duc Thinh 7 Aug 28, 2022
NV_MVVM-C is a template file generator. This can reduce the time taken to write the boilerplate code and create the files.

NV_MVVM-C Template, is an MVVM-C Boilerplate generator which will help you generate all the necessary files for your project architected in MVVM-C.

Nikhil Vinod 9 Sep 6, 2022
Read iOS 15 privacy insight '.ndjson' file into your human brain.

Insight Read iOS 15 privacy insight '.ndjson' file into your human brain. Written in SwiftUI. Feature Compile records into app summary Relink app info

Lakr Aream 151 Nov 11, 2022
Read colors from Xcode assets file.

XcodePalette Read colors from Xcode assets file. How to Use Download the XcodePalette.Executable.zip of the latest release. Extract the XcodePalette U

iMoeNya 0 Nov 12, 2021