Skip to content

Latest commit

 

History

History
92 lines (81 loc) · 2.23 KB

File metadata and controls

92 lines (81 loc) · 2.23 KB

CSV support in Pharo

Currently, Pharo provides one main framework to handle the CSV format: NeoCSV.

NeoCSV

NeoJSON is actually maintained by Sven Van Caekenberghe on github. This section shows some quick examples but there is a great documentation made by Sven and a chapter in Enterprise Pharo (chapter 7).

NeoCSV provides utilities to map Smalltalk objects to CSV lines, this page does not cover this topic to avoid duplication with the great documentation available in Sven's documentation and Enterprise Pharo (chapter 7). Check it out if you need to use such feature!

Install

To install NeoCSV, simply execute the following code snippet in a playground:

Metacello new
	repository: 'github://svenvc/NeoCSV/repository';
	baseline: 'NeoCSV';
	load

Parse CSV

  • From String:
str := 'id, name
0, Julien
1, Cyril
2, Guillaume
'.
str readStreamDo: [ :s |
	(NeoCSVReader on: s)
		skipHeader;
		addIntegerField;
		addField;
		upToEnd ]
  • From Stream:
stream := 'id, name
0, Julien
1, Cyril
2, Guillaume
' readStream.

(NeoCSVReader on: stream)
	skipHeader;
	addIntegerField;
	addField;
	upToEnd
  • Read from CSV file:
'/path/to/file.csv' asFileReference
	readStreamDo: [ :readStream |
		(NeoCSVReader on: readStream)
			skipHeader;
			addIntegerField;
			addField;
			upToEnd ]

Generate CSV

Let data be defined as:

data := #(
(0 'Julien')
(1 'Cyril')
(2 'Guillaume')).
  • To generate a CSV String:
String streamContents: [ :writeStream |
	(NeoCSVWriter on: writeStream)
		writeHeader: #(id name);
		nextPutAll: data ]
  • To generate CSV on a Stream:
(NeoCSVWriter on: writeStream)
	writeHeader: #(id name);
	nextPutAll: data
  • To write a CSV file:
'/path/to/file.csv' asFileReference
	writeStreamDo: [ :writeStream |
		(NeoCSVWriter on: writeStream)
 			writeHeader: #(id name);
			nextPutAll: data ]