Lasso Soft Inc. > Home

[csv]

Linkcsv
AuthorJason Huck
CategoryData Type
Version8.x
Licensehttp://opensource.org/licenses/artistic-license.php
Posted04 Apr 2006
Updated26 Apr 2006
More by this author...

Description

This is a basic type for reading, writing, and serving CSV files. I've updated the parsing method to use Daniel James' method from this post.


Instance Variables

->fields - An array containing the column names for the CSV file. Will default to [field_names] on creation if/when possible.

->rows - An array of arrays containing the data for the CSV file. Will default to [rows_array] on creation if/when possible.

->loadpath - String, the path to a CSV file to parse into the type.

->titlerow - Boolean, whether or not the CSV file contains a title row. Pertains to both loading and saving files. Defaults to false.

->savepath - String, where to save the CSV file.

->filename - String, the name to use when saving the file. Defaults to "results.csv."


Member Tags/Methods

->parseline - Parses an individual line of a loaded file. Used internally by ->load.

->load - Loads a CSV file from the given path. Optionally accepts a boolean 'titlerow' parameter indicating whether or not the source file contains a title row.

->output - Returns the contents of the object formatted as a CSV file. Used internally by ->save and ->serve.

->save - Saves a CSV file to the given path.

->serve - Serves a CSV file to the browser using [file_serve].

->addrow - Accepts an array to add to ->rows.

Sample Usage

var('fieldnames') = array('Color','Number','Size');
var('data') = array(
	array('Red',1,'small'),
	array('Green',2,'medium'),
	array('Blue',3,'large'),
	array('Black',4,'extra large with "some" quotes')
);

var('stuff') = csv(
	-fields=$fieldnames,
	-rows=$data,
	-titlerow=true
);
	
$stuff->addrow(array('Orange',5,'tiny'));

$stuff->save('atestfile.csv');

$stuff = null;
$stuff = csv;
$stuff->load('atestfile.csv');
$stuff->output;

Source Code

Click the "Download" button below to retrieve a copy of this tag, including the complete documentation and sample usage shown on this page. Place the downloaded ".inc" file in your LassoStartup folder, restart Lasso, and you can begin using this tag immediately.

define_type(
	'csv',
	-prototype,
	-description='A basic type for reading, writing, and serving CSV files.'
);
	local(
		'fields' = array,
		'rows' = array,
		'loadpath' = string,
		'titlerow' = false,
		'savepath' = string,
		'filename' = 'results.csv'
	);
	
	define_tag(
		'onCreate',
		-optional='filename',
		-type='string',
		-optional='loadpath',
		-type='string',
		-optional='titlerow',
		-type='boolean',
		-optional='savepath',
		-type='string',
		-optional='fields',
		-type='array',
		-optional='rows',
		-type='array'
	);		
		if(local_defined('fields'));
			self->fields = #fields;
		else(field_names->size);
			self->fields = field_names;
		/if;
		
		if(local_defined('rows'));
			self->rows = #rows;
		else(rows_array->size);
			self->rows = rows_array;
		/if;
		
		local_defined('filename') ? self->filename = #filename;
		local_defined('savepath') ? self->savepath = #savepath;
		local_defined('titlerow') ? self->titlerow = #titlerow;
		
		local_defined('loadpath') ? self->load( 
			-loadpath=#loadpath,
			-titlerow=self->titlerow
		);
	/define_tag;

	define_tag(
		'parseline', 
		-required='line'
	);
		local(
			'field' = string, 
			'i' = null, 
			'row' = array
		);
		
		iterate(
			string_findregexp(
				#line, 
				-find = '"(?:[^"]|"")*"|[^,]*|,'
			), 
			#i
		);
			if(#i == ',');
				#row->insertlast(#field);
				#field = '';
				
			else(#i->beginswith('"') && #i->endswith('"'));
				#field += #i->substring(2, #i->size - 2)->replace('""', '"')&;
				
			else;
				#field += #i;
				
			/if;
		/iterate;
		
		#row->insertlast(#field);
		
		return(#row);
	/define_tag;

	define_tag(
		'load',
		-required='loadpath',
		-type='string',
		-optional='titlerow',
		-type='boolean'
	);
		fail_if(
			(!file_exists(#loadpath) || !file_read(#loadpath)),
			file_currenterror( -errorcode),
			file_currenterror
		);
		
		self->loadpath = #loadpath;
		local_defined('titlerow') ? self->titlerow = #titlerow;
		
		local('in') = file_read(#loadpath);
		
		iterate(#in->split('\r\n'), local('line'));
			self->titlerow && loop_count == 1 
				? self->fields = self->parseline(#line)
				| self->rows->insert(self->parseline(#line));
		/iterate;
	/define_tag;
	
	define_tag('output');
		local('out' = string);
		
		if(self->titlerow && self->fields->size);			
			iterate(self->fields, local('f'));
				#out += '"' + #f + '"';				
				loop_count == self->fields->size ? #out += '\r\n' | #out += ',';
			/iterate;
		/if;
	
		iterate(self->rows, local('r'));
			iterate(#r, local('f'));
				#f = string(#f);
				#f->replace('"','""')&replace('\r\n','\n')&replace('\r','\n');
				#out += '"' + #f + '"';				
				loop_count == #r->size ? #out += '\r\n' | #out += ',';
			/iterate;
		/iterate;
		
		#out->removetrailing('\r\n');
		
		return(@#out);
	/define_tag;
	
	define_tag(
		'save',
		-optional='savepath'
	);
		local_defined('savepath') ? self->savepath = #savepath;
		
		file_create(
			self->savepath, 
			-fileoverwrite
		);
		
		file_write(
			self->savepath,
			self->output,
			-fileoverwrite
		);
	/define_tag;
	
	define_tag(
		'serve',
		-optional='filename'
	);
		local_defined('filename') ? self->filename = #filename;
		
		file_serve(
			self->output,
			-file=self->filename,
			-type='text/csv'
		);
	/define_tag;
	
	define_tag(
		'addrow',
		-required='data',
		-type='array'
	);
		self->rows->insert(#data);
	/define_tag;
/define_type;

Related Tags

Comments

28 Aug 2013, Jonathan Guthrie

Lasso 9 "port"

A Lasso 9 port (partial rewrite) is available at: https://github.com/iamjono/csv

Thanks Jason!

30 Mar 2009, Mark Palmer

Normalise line endings

Hi,
This is great thanks.

I made one small tweak to normalise the line ending (it seems to be expecting \r\n_).

In the load tag
#in->Replace('\n','\r');
#in->Replace('\r','\r\n');


20 May 2008, Peer Schmitz

This crashes...

Hi! If I export 1-10 lines of my records (each record having 30 fields) it works. Anything more and Lasso crashes (I get an internal server error).
I think this is a memory problem.

How can I increase the available memory to csv/Lasso?
Thanks,
P. Schmitz (pschmitz A T hostnet.ch)

20 Sep 2007, Daniela Kalb

Great! Great!

thx for this type! A million hugs!

Please log in to comment

Subscribe to the LassoTalk mail list

LassoSoft Inc. > Home

 

 

©LassoSoft Inc 2015 | Web Development by Treefrog Inc | PrivacyLegal terms and Shipping | Contact LassoSoft