Extracting data (to CSV) from Javascript HTML - javascript

Currently, I am making a website that read a CSV files and put it in the HTML. Now, I want to extract an array from my javascript HTML, to create a csv file. Is it possible to do that? If possible, please guide me.

Create a Blob and save it using the download attribute in links
var saveData = (function () {
var a = document.createElement('a')
a.hidden = true
document.body.appendChild(a)
return function (data, fileName) {
var blob = new Blob([data], {type: 'octet/stream'})
var url = URL.createObjectURL(blob)
a.href = url
a.download = fileName
a.click()
URL.revokeObjectURL(url)
}
}())
// I leave it up to you to create the data
// necessary for creating the csv data.
//
// data can also be array buffers blob or
// other stuff the blob constructor can take.
var data = 'abc,123'
var fileName = "my-download.csv"
saveData(data, fileName)

Use the below plugin from the link and export easily.
http://www.jqueryscript.net/demo/Exporting-Html-Tables-To-CSV-XLS-XLSX-Text-TableExport/

You Can use the below code for exporting HTML table data to Excel with javascript.
Sample Html Code:-
<button id="btnExport">Export to xls</button>
<br />
<br />
<div id="table_wrapper">
<table border="1" cellspacing="0" bordercolor="#222" id="list">
<tbody>
<tr class="header">
<th>user_id</th>
<th>firstname</th>
<th>lastname</th>
</tr>
<tr>
<td>1</td>
<td>Test</td>
<td>User1</td>
</tr>
<tr>
<td>2</td>
<td>Test</td>
<td>User 2</td>
</tr>
<tr>
<td>3</td>
<td>Test</td>
<td>User 3</td>
</tr>
</tbody>
</table>
Javascript code:-
$("#btnExport").click(function(e) {
e.preventDefault();
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('table_wrapper');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
var a = document.createElement('a');
a.href = data_type + ', ' + table_html;
a.download = 'exported_table_data + '.xls';
a.click();
});
I think it will help u..

Related

Exporting Html Table containing hyperlinks to CSV by persisting the hyperlinks in csv file

I want to export the html table to csv file. In my case Html table consists of hyperlinks. While exporting html table to csv either the text or link is getting persisted in the table. I want the text to be persisted in the csv file as a hyperlink. Explored multiple solutions but none works. Tried adding whole anchor tag to variable and then adding to row, but whole anchor tag is appearing in the table in csv file. Needed quick help.
This is how the csv file should look like
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style="color:green">GeeksForGeeks</h1>
<h2>Table to CSV converter</h2>
<table border="1" cellspacing="0" cellpadding="10">
<tr>
<th>Name</th>
<th>age</th>
<th>place</th>
</tr>
<tr>
<td>Laxman</td>
<td>19</td>
<td>Hyderabad</td>
</tr>
<tr>
<td>Dhoni</td>
<td>22</td>
<td>Ranchi</td>
</tr>
<tr>
<td>Kohli</td>
<td>25</td>
<td>Delhi</td>
</tr>
</table>
<br><br>
<button type="button" onclick="tableToCSV()">
download CSV
</button>
</center>
<script type="text/javascript">
function tableToCSV() {
// Variable to store the final csv data
var csv_data = [];
// Get each row data
var rows = document.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
// Get each column data
var cols = rows[i].querySelectorAll('td,th');
// Stores each csv row data
var csvrow = [];
for (var j = 0; j < cols.length; j++) {
// Get the text data of each cell
// of a row and push it to csvrow
var links = cols[j].getElementsByTagName('a');
if (links.length > 0) {
var link = links[0].getAttribute('href');
var text = cols[j].textContent;
var result = text.link(link)
csvrow.push(result);
} else {
var cellData = cols[j].textContent;
csvrow.push(cellData);
}
}
// Combine each column value with comma
csv_data.push(csvrow.join(","));
}
// Combine each row data with new line character
csv_data = csv_data.join('\n');
// Call this function to download csv file
downloadCSVFile(csv_data);
}
function downloadCSVFile(csv_data) {
// Create CSV file object and feed
// our csv_data into it
CSVFile = new Blob([csv_data], {
type: "text/csv"
});
// Create to temporary link to initiate
// download process
var temp_link = document.createElement('a');
// Download csv file
temp_link.download = "GfG.csv";
var url = window.URL.createObjectURL(CSVFile);
temp_link.href = url;
// This link should not be displayed
temp_link.style.display = "none";
document.body.appendChild(temp_link);
// Automatically click the link to
// trigger download
temp_link.click();
document.body.removeChild(temp_link);
}
</script>
</body>
</html>

Export HTML form to Excel CSV not working with Element.append() method

Following my previous query:
HTML form output as a table
I would like to export my HTML form output to Excel.
I found several examples on the web and tried some of them...
https://www.revisitclass.com/css/how-to-export-download-the-html-table-to-excel-using-javascript/
https://www.codexworld.com/export-html-table-data-to-csv-using-javascript/
https://odoepner.wordpress.com/2012/04/09/export-to-html-table-as-csv-file-using-jquery/
In all cases, I get only the column titles instead of other rows, as you can see below:
There is something wrong with the Element.append() which can't be picked up properly
My code looks as follows:
<table id="opresults" class="outputtable"><p class="outputtablehead">Survey Form - output</p>
<tr class="colname">
<th class="question">Form question</th>
<th colspan="2" class="answer">Answer</th>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
<script>
const resultsList = document.getElementById('opresults')
const matches = document.querySelectorAll("fieldset");
new URLSearchParams(window.location.search).forEach((value, name) => {
resultsList.append(document.createElement('tbody'))
resultsList.append(`${name}`)
resultsList.append(document.createElement('td'))
resultsList.append(`${value}`)
resultsList.append(document.createElement('br'))
})
</script>
and another script, which exports the file to .csv is included here:
https://jsfiddle.net/c0urwa5g/1/
Is there any way to include the append() method in this .csv export?
As per another example:
How to export JavaScript array info to csv (on client side)?
It looks like I have to define the column and row names. Unfortunately, I can't here, because they are input-dependant. Is there a way to solve this issue?
The code with another approach is here:
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
// CSV file
csvFile = new Blob([csv], {type: "text/csv"});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Hide download link
downloadLink.style.display = "none";
// Add the link to DOM
document.body.appendChild(downloadLink);
// Click download link
downloadLink.click();
}
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
You aren't creating row elements or inserting cells in those row elements or inserting text into the cells you are creating
You are trying to append everything directly into the table element and that won't work.
You can simplify this using Table.insertRow() and Row.insertCell()
initDemo()
const resultsList = document.getElementById('opresults');
new URLSearchParams(window.location.search).forEach((value, name) => {
const row = resultsList.insertRow();
[name, value].forEach(v => row.insertCell().textContent = v);
})
// for demo only - creates initial url search params
function initDemo() {
const params = new URLSearchParams([
["issue_1", "answer_1"],
["thing_2", "answer_2"]
]);
history.pushState(null, null, '?' + params.toString())
}
<p class="outputtablehead">Survey Form - output</p>
<table id="opresults" class="outputtable" border="1">
<tr class="colname">
<th class="question">Form question</th>
<th colspan="2" class="answer">Answer</th>
</tr>
</table>

How to use this HTML table to excel function in jquery / javascript

this is the fiddle
https://jsfiddle.net/shaswatatripathy/ym4egje0/7/
How to use the tableToExcel function and make it work in Internet Explorer 11
Also It should work in Google chrome thats better .
Cant use any Iframe
Objective
Have to export table to excel file for IE and after much searching found this function from
Generate excel sheet from html tables using jquery
but not able to use it .
HTML
<input id="btnExport" type="button" value = "Generate File" />
<table id="table">
<th>
<tr>
<td>coulmn1</td>
<td>column2</td>
</tr>
</th>
<tbody>
<tr>
<td>row1column1</td>
<td>row1column2</td>
</tr>
</tbody>
</table>
JS
$("#btnExport").click(function (e) {
TableToExcel;
});
var TableToExcel = (function () {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table cellspacing="0" rules="rows" border="1" style="color:Black;background-color:White;border-color:#CCCCCC;border-width:1px;border-style:None;width:100%;border-collapse:collapse;font-size:9pt;text-align:center;">{table}</table></body></html>'
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
return function (table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
if (navigator.msSaveBlob) {
var blob = new Blob([format(template, ctx)], { type: 'application/vnd.ms-excel', endings: 'native' });
navigator.msSaveBlob(blob, 'export.xls')
} else {
window.location.href = uri + base64(format(template, ctx))
}
}
})()

Exporting HTML table to Excel using Javascript

I am exporting HTML table to xls foramt. After exporting if you open it in Libre Office, it works fine but the same opens a blank screen in Microsoft Office.
I don't want a jquery solution please provide any javascript solution.
Please help.
function fnExcelReport() {
var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange;
var j = 0;
tab = document.getElementById('table'); // id of table
for (j = 0; j < tab.rows.length; j++) {
tab_text = tab_text + tab.rows[j].innerHTML + "</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text = tab_text + "</table>";
tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table
tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html", "replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, "Say Thanks to Sumit.xls");
} else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();"> EXPORT
</button>
<table id="table">
<thead>
<tr>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<td>31</td>
<td>32</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>41</td>
<td>42</td>
<td>43</td>
<td>44</td>
</tr>
</tbody>
</table>
On 2016-07-12, Microsoft pushed a security update for Microsoft Office. One of the effects of this update was to prevent HTML files from non-trusted domains from being opened by Excel, because they cannot be opened in Protected mode.
There is ALSO a registry setting that prevents Excel from opening files with the .XLS file extension whose contents do not match the official XLS file format, though it defaults to 'warn', not 'deny'.
Prior to this change, it was possible to save HTML data to a file with an XLS extension, and Excel would open it correctly - possibly giving a warning first that the file did not match the Excel format, depending on the user's value for the ExtensionHardening registry key (or related config values).
Microsoft has made a knowledge-base entry about the new behavior with some suggested workarounds.
Several web applications that previously relied on exporting HTML files as XLS have run into trouble as a result of the update - SalesForce is one example.
Answers from before July 12th 2016 to this and similar questions are likely to now be invalid.
It's worth noting that files produced ON THE BROWSER from remote data do not fall afoul of this protection; it only impedes files downloaded from a remote source that is not trusted. Therefore one possible approach is to generate the .XLS-labelled HTML file locally on the client.
Another, of course, is to produce a valid XLS file, which Excel will then open in Protected mode.
UPDATE: Microsoft has released a patch to correct this behavior: https://support.microsoft.com/en-us/kb/3181507
SheetJS seems perfect for this.
To export your table as an excel file use the code in this link(along with SheetJS)
Just plug in your table element's id into export_table_to_excel
See Demo
If CSV format is good for you, here is an example.
Ok...I just read a comment where you explicitly say it isn't good for you. My bad for not learning to read before coding.
As far I know, Excel can handle CSV.
function fnExcelReport() {
var i, j;
var csv = "";
var table = document.getElementById("table");
var table_headings = table.children[0].children[0].children;
var table_body_rows = table.children[1].children;
var heading;
var headingsArray = [];
for(i = 0; i < table_headings.length; i++) {
heading = table_headings[i];
headingsArray.push('"' + heading.innerHTML + '"');
}
csv += headingsArray.join(',') + ";\n";
var row;
var columns;
var column;
var columnsArray;
for(i = 0; i < table_body_rows.length; i++) {
row = table_body_rows[i];
columns = row.children;
columnsArray = [];
for(j = 0; j < columns.length; j++) {
var column = columns[j];
columnsArray.push('"' + column.innerHTML + '"');
}
csv += columnsArray.join(',') + ";\n";
}
download("export.csv",csv);
}
//From: http://stackoverflow.com/a/18197511/2265487
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();">EXPORT
</button>
<table id="table">
<thead>
<tr>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<td>31</td>
<td>32</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>41</td>
<td>42</td>
<td>43</td>
<td>44</td>
</tr>
</tbody>
</table>
add this to your head:
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
and add this as your javascript:
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
Jfiddle: http://jsfiddle.net/cmewv/537/
try this
<table id="exportable">
<thead>
<tr>
//headers
</tr>
</thead>
<tbody>
//rows
</tbody>
</table>
Script for this
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
You can use tableToExcel.js to export table in excel file.
This works in a following way :
1). Include this CDN in your project/file
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel#v1.0.4/dist/tableToExcel.js"></script>
2). Either Using JavaScript:
<button id="btnExport" onclick="exportReportToExcel(this)">EXPORT REPORT</button>
function exportReportToExcel() {
let table = document.getElementsByTagName("table"); // you can use document.getElementById('tableId') as well by providing id to the table tag
TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
name: `export.xls`, // fileName you could use any name
sheet: {
name: 'Sheet 1' // sheetName
}
});
}
3). Or by Using Jquery
<button id="btnExport">EXPORT REPORT</button>
$(document).ready(function(){
$("#btnExport").click(function() {
let table = document.getElementsByTagName("table");
TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
name: `export.xls`, // fileName you could use any name
sheet: {
name: 'Sheet 1' // sheetName
}
});
});
});
You may refer to this github link for any other information
https://github.com/linways/table-to-excel/tree/master
or for referring the live example visit the following link
https://codepen.io/rohithb/pen/YdjVbb
This will download the export.xls file
Hope this will help someone :-)
<hrml>
<head>
<script language="javascript">
function exportF() {
//Format your table with form data
document.getElementById("input").innerHTML = document.getElementById("text").value;
document.getElementById("input1").innerHTML = document.getElementById("text1").value;
var table = document.getElementById("table");
var html = table.outerHTML;
var url = 'data:application/vnd.C:\\Users\WB-02\desktop\Book1.xlsx,' + escape(html); // Set your html table into url
var link = document.getElementById("downloadLink");
link.setAttribute("href", url);
link.setAttribute("download", "export.xls"); // Choose the file name
link.click(); // Download your excel file
return false;
}
</script>
</head>
<body>
<form onsubmit="return exportF()">
<input id="text" type="text" />
<input id="text1" type="text" />
<input type="submit" />
</form>
<table id="table" style="display: none">
<tr>
<td id="input">
<td id="input1">
</td>
</tr>
</table>
<a style="display: none" id="downloadLink"></a>
</body>
</html>
İf you have a too much column , try to use this code. You can split easily.
function iterate( tab, startIndex , rowCount){
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
J=startIndex;
for(j = startIndex ; j < rowCount ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
}
function fnExcelReport()
{
var indirilecekSayi = 250;
var toplamSatirSayisi = 0;
var baslangicSAyisi = 0;
var sonsatirsayisi = 0;
tab = document.getElementById('myTable'); // id of table
var maxRowCount = tab.rows.length;
toplamSatirSayisi = maxRowCount;
sonsatirsayisi=indirilecekSayi;
var kalan = toplamSatirSayisi % indirilecekSayi;
var KalansızToplamSatir=ToplamSatirSayisi-kalan;
var kacKati=Tsh / indirilecekSayi;
alert(maxRowCount);
alert(kacKati);
for (let index = 0; index <= kacKati; index++) {
if (index==kacKati) {
baslangicSAyisi =sonsatirsayisi;
sonsatirsayisi=sonsatirsayisi+kalan;
iterate(tab, baslangicSAyisi, sonsatirsayisi);
}else{
iterate(tab , baslangicSAyisi , sonsatirsayisi);
baslangicSAyisi=sonsatirsayisi;
sonsatirsayisi=sonsatirsayisi+indirilecekSayi;
if(sonsatirsayisi>ToplamSatirSayisi){
sonsatirsayisi=baslangicSAyisi;
}
}
}
}

Import File Preview

I have this form which import transactions of the user. I enhance the form where user can preview the list of transactions they will be importing to their account.
Sample:
The above sample preview is for the QIF file format which I successfully done.
Now I'm trying to preview the OFX file format and I'm having difficulty to arrange it in a table and get the exact value.
Here are my codes:
<input type="file" name="transactions" id="id_transactions">
<div style="display:none;width:335px;" id="preview-box">
<h4 class="thin" class="black">Import Preview</h4>
<table class="simple-table responsive-table footable">
<thead>
<tr>
<th scope="col" width="10%"><small class="black">Date</small></th>
<th scope="col" width="10%"><small class="black">Amount</small></th>
<th scope="col" width="20%"><small class="black">Payee</small></th>
</tr>
</thead>
</table>
<div class="scrollable" style="height:100px">
<table class="simple-table responsive-table footable">
<tbody id="preview-table"></tbody>
</table>
</div><br/>
</div>
<script>
$('#id_transactions').change(function() {
var upload = document.getElementById('id_transactions')
var files = upload.files
if (files != undefined) {
var reader = new FileReader();
reader.onload = function(e) {
var extension = upload.value.split('.').pop().toLowerCase()
var lineSplit = e.target.result.split("\n");
var payee = ''
var date
var amount
var content = "";
var content1 = "";
var content2 = "";
if(extension == "qif"){
// for qif preview
}else if(extension == "ofx"){
$('#preview-box').show(500)
for(var i = 1; i < lineSplit.length; i++) {
//I'm stuck here....
}
}
$('#preview-table').html(content);
};
reader.readAsText(files.item(0));
}
});
</script>
sample.ofx
OFXHEADER:100
DATA:OFXSGML
VERSION:103
SECURITY:NONE
ENCODING:USASCII
CHARSET:1252
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE
<OFX>
<SIGNONMSGSRSV1>
<SONRS>
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<DTSERVER>20071015021529.000[-8:PST]
<LANGUAGE>ENG
<DTACCTUP>19900101000000
<FI>
<ORG>MYBANK
<FID>01234
</FI>
</SONRS>
</SIGNONMSGSRSV1>
<BANKMSGSRSV1>
<STMTTRNRS>
<TRNUID>23382938
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<STMTRS>
<CURDEF>USD
<BANKACCTFROM>
<BANKID>987654321
<ACCTID>098-121
<ACCTTYPE>SAVINGS
</BANKACCTFROM>
<BANKTRANLIST>
<DTSTART>20070101
<DTEND>20071015
<STMTTRN>
<TRNTYPE>CREDIT
<DTPOSTED>20070315
<DTUSER>20070315
<TRNAMT>200.00
<FITID>980315001
<NAME>DEPOSIT
<MEMO>automatic deposit
</STMTTRN>
<STMTTRN>
<TRNTYPE>CREDIT
<DTPOSTED>20070329
<DTUSER>20070329
<TRNAMT>150.00
<FITID>980310001
<NAME>TRANSFER
<MEMO>Transfer from checking
</STMTTRN>
<STMTTRN>
<TRNTYPE>PAYMENT
<DTPOSTED>20070709
<DTUSER>20070709
<TRNAMT>-100.00
<FITID>980309001
<CHECKNUM>1025
<NAME>John Hancock
</STMTTRN>
</BANKTRANLIST>
<LEDGERBAL>
<BALAMT>5250.00
<DTASOF>20071015021529.000[-8:PST]
</LEDGERBAL>
<AVAILBAL>
<BALAMT>5250.00
<DTASOF>20071015021529.000[-8:PST]
</AVAILBAL>
</STMTRS>
</STMTTRNRS>
</BANKMSGSRSV1>
</OFX>
Anyone who already done this?
UPDATE:
Output:
You know what, this OFX file format looks a lot like an XML in the second part, with an empty line separating the two parts (correct me if I'm wrong, I don't know this format).
Inside the onload event listener, try something like this:
var ofxParts = e.result.split("\r?\n\r?\n"), ofxHeaders, ofxDocument;
ofxHeaders = JSON.parse("{"
+ ofxParts[0].replace(/(\w+) *: *(\w*)/g, "\"$1\": \"$2\"")
.replace(/\r?\n/g, ", ") + "}");
ofxDocument = new DOMParser().parseFromString(ofxParts[1]
.replace(/<(\w+)>(?!\n|\r\n)(.*)/g, "<$1>$2</$1>"));
Now you should have the OFX headers in a useful Javascript object like this:
ofxHeaders = {
"OFXHEADER": "100",
"DATA": "OFXSGML",
"VERSION": "103",
"SECURITY": "NONE",
"ENCODING": "USASCII",
"CHARSET": "1252",
"COMPRESSION": "NONE",
"OLDFILEUID": "NONE",
"NEWFILEUID": "NONE"
};
and you can crawl and select your OFX document with document.evaluate like any other XML.
This should all be available as far as you're using FileReader. Except IE10, which doesn't support document.evaluate. You'll have to create an ActiveXObject and use loadXML if you want to use XPath.
Or you can just use jQuery:
var $ofx = $.parseXML(ofxParts[1].replace(/<(\w+)>(?!\n|\r\n)(.*)/g, "<$1>$2</$1>"));
Edit: You can now create the rows of the table in this kind of way:
var $xfers = $ofx.find("STMTTRN");
content = $xfers.map(function(xf) {
var $xf = $(xf), date = $xf.find("DTPOSTED").text();
return "<tr><td>" + date.substring(4, 6) + "/" + date.substring(6)
+ "/" + date.substring(0, 4) + "<td></td>" + $xf.find("NAME").text()
+ "</td><td>" + $xf.find("TRNAMT").text() + "</td></tr>";
}).join("");

Categories