FileAPI. CSV reader/parser.
by Alexey Demin
HTML
<div id="dragArea">
<div id="panel">This browser doesnt support the File API</div>
<div id="content"></div>
<div id="console"></div>
</div>
CSS
#dragArea {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #efefef;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
padding: 5px;
white-space: pre;
}
#content {
position: absolute;
top: 45px;
left: 5px;
right: 5px;
bottom: 55px;
border: 1px solid #adadad;
border-bottom: 0;
background-color: #fff;
box-shadow: inset 0 0 1px 1px #E4E4E4;
padding: 5px;
overflow: scroll;
}
#panel {
position: absolute;
top: 5px;
left: 5px;
right: 5px;
}
#console {
position: absolute;
bottom: 5px;
left: 5px;
right: 5px;
height: 40px;
padding: 5px;
font-family: monspace;
font-size: 10px;
border: 1px solid #adadad;
border-top: 0;
background-color: #fff;
box-shadow: inset 0 0 1px 1px #E4E4E4;
overflow: scroll;
}
JavaScript
// http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data
function CSVToArray(strData, strDelimiter) {
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ";");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"),
"gi");
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [
[]
];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec(strData)) {
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push([]);
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[2]) {
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[2].replace(
new RegExp("\"\"", "g"),
"\"");
} else {
// We found a non-quoted...