I have written a function in javascript that identifies a table in a HTML webpage, parses through the data and downloads it as comma separated values that retains the correct structure of the table. I was hoping there would be a simple way to download the tables as a csv file instead, making sure it keeps the correct structure (i.e. blank cells when present etc).
function downloadTableData(){
try{
var file_string = "";
var table_number = window.prompt("Table number:") - 1;
var column_names = document.getElementsByTagName("table")[table_number].children[0].children[0].children;
col_names = "";
for(var i=0; i<column_names.length; i++){
col_names += column_names[i].innerText+",";
}
file_string += col_names += "\n";
var table_rows = document.getElementsByTagName("table")[table_number].children[1].children;
var extracted_rows = [];
for(var row_i=0; row_i<table_rows.length; row_i++){
var row_vals = ""
for(var col_i=0; col_i<table_rows[row_i].children.length; col_i++){
row_vals += table_rows[row_i].children[col_i].innerText + ",";
}
file_string += row_vals+"\n";
extracted_rows.push(row_vals);
}
var textInput = file_string;
alert('Table successfully detected');
var filename = window.prompt("Filename:");
var element = document.createElement('a');
element.setAttribute('href','data:text/plain;charset=utf-8, ' + encodeURIComponent(textInput));
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
} catch(err){
alert('No table detected');
}