killhour killhour - 1 year ago 49
HTML Question

Need to export tables inside a <div> as excel, keeping filled-in input and option data

I have a page that takes some selections in javascript and makes a recommendation based on the inputs. Some of my customers want to be able to save this data in excel format, but I'm running into issues retrofitting that.

Here is the code that I found to export the HTML in a DIV as an XLS:

$('btnExport').addEvent('click', function(e){
//getting values of current time for generating the file name
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
//creating a temporary HTML link element (they support setting file names)
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/';
var table_div = document.getElementById('dvData');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name = 'exported_table_' + postfix + '.xls';
//triggering the function;
//just in case, prevent default behaviour

This almost does what I need it to, but I would like to be able to preserve the initial selections (both drop downs and fields) as their values in the final output. I found some related code to go in and replace those tags with their values, but that affects the page itself, not the output.

var inputs = document.querySelectorAll('select');
for (var i = 0; i < inputs.length; i++) {
var text = document.createTextNode(inputs[i].value);
inputs[i].parentNode.replaceChild(text, inputs[i]);

How do I combine these two functions into something that makes sense? The data I need to export is split across multiple tables. I found some solutions leveraging jquery, but I'm using mootools on the site, and combining the two seems to break things.

Answer Source

I will give you a hint for a lazy solution. On page load clone that div with cloneNode and keep it as a variable. When you need to do the export just export that reference (not the actual div).

On the other hand, if you need to keep some other information entered by user still clone the node and run through all the fields and dropdowns within a cloned instance and set them back to default. If you need a reference to each default value of each dropdown you can do so with some kind of data-* attribute. Then again, export the cloned node.