Skip to content

Instantly share code, notes, and snippets.

@mjhagen
Created April 26, 2021 14:47
Show Gist options
  • Save mjhagen/cfd620a4c79f46a650ec0dbe1b429009 to your computer and use it in GitHub Desktop.
Save mjhagen/cfd620a4c79f46a650ec0dbe1b429009 to your computer and use it in GitHub Desktop.
CSV Parser using Univocity in CFML / ColdFusion
component accessors=true {
public any function getCSVParser(
boolean delimiterDetectionEnabled = true,
boolean headerExtractionEnabled = true,
boolean lineSeparatorDetectionEnabled = true,
boolean quoteDetectionEnabled = true
) {
var csvParserSettings = createObject( 'java', 'com.univocity.parsers.csv.CsvParserSettings' );
csvParserSettings.setDelimiterDetectionEnabled( delimiterDetectionEnabled );
csvParserSettings.setHeaderExtractionEnabled( headerExtractionEnabled );
csvParserSettings.setLineSeparatorDetectionEnabled( lineSeparatorDetectionEnabled );
csvParserSettings.setQuoteDetectionEnabled( quoteDetectionEnabled );
return createObject( 'java', 'com.univocity.parsers.csv.CsvParser' ).init( csvParserSettings );
}
public any function getJavaFileReader( csvFile ) {
return createObject( 'java', 'java.io.FileReader' ).init( csvFile );
}
public array function readCsvData( required string csvFile ) {
return getCSVParser().parseAll( getJavaFileReader( csvFile ) );
}
public array function readCsvDataAsRecords( required string csvFile ) {
return getCSVParser().parseAllRecords( getJavaFileReader( csvFile ) );
}
}
@mjhagen
Copy link
Author

mjhagen commented Apr 26, 2021

Implement like this:

var csvParser = new csv();
var customers = csvParser.readCsvData( 'path/to/customers.csv' );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment