fabianmoronzirfas
8/16/2016 - 5:53 AM

README.md

/* global File $ */
/* eslint-disable new-cap */
var textlines = [];
var filepath = 'data.csv';
var file = File(File($.fileName).parent.fsName + '/'+  filepath);
if(file.exists) $.writeln('foo');
file.encoding = 'UTF8';
file.lineFeed = 'Macintosh';

file.open('r',undefined,undefined);
var content = file.read();
$.writeln(content);

file.close();

num,name,w,f,h
1,A,1,4,2
2,B,2,3,1
3,C,3,2,4
4,D,4,1,3
5,E,3,2,2
6,F,2,3,1

csv reading in extendscript

This scipt asumes that the data.csv is next to the index.js. The content of data.csv is:

numnamewfh
1A142
2B231
3C324
4D413
5E322
6F231

This is the quick and dirty approach. For data you don't know how it is formated I suggest using a library like github.com/Rich-Harris/BabyParse. With minor adjustments it works well in ExtendScript.

/* global File $ */
/* eslint-disable new-cap */
// tested on osx
var file = File(File($.fileName).parent.fsName + '/data.csv'); // get the file
file.encoding = 'UTF8'; // set some encoding
file.lineFeed = 'Macintosh'; // set the linefeeds
file.open('r',undefined,undefined); // read the file
var content = file.read(); // get the text in it
file.close(); // close it again
var lines = content.split('\n');// split the lines (windows should be '\r')
var data = [];// will hold the data
var keys = lines[0].split(','); // get the heads
// loop the data
for(var i = 1; i < lines.length;i++){
  var obj = {}; // temp object
  var cells = lines[i].split(',');// get the cells
  // assign them to the heads
  obj[keys[0]] = cells[0];
  obj[keys[1]] = cells[1];
  obj[keys[2]] = cells[2];
  obj[keys[3]] = cells[3];
  obj[keys[4]] = cells[4];
  data.push(obj); // add to data
  }

$.writeln(data.toSource()); // show what we got

The output is:

[({num:"1", name:"A", w:"1", f:"4", h:"2"}), ({num:"2", name:"B", w:"2", f:"3", h:"1"}), ({num:"3", name:"C", w:"3", f:"2", h:"4"}), ({num:"4", name:"D", w:"4", f:"1", h:"3"}), ({num:"5", name:"E", w:"3", f:"2", h:"2"}), ({num:"6", name:"F", w:"2", f:"3", h:"1"})]