Export expandable table to excel file using Javascript - javascript

I have an expandable table in html:
How can I convert it into excel file with grouping, something like this:

Im not to sure about the grouping in XLS but the main way we convert data into XL is to use CSV
You can parse the data from your HTML into an array then export that array to CSV
Here is the code to make your html table downloadable to CSV
var data = [
['Foo', 'programmer'],
['Bar', 'bus driver'],
['Moo', 'Reindeer Hunter']
];
function download_csv() {
var csv = 'Name,Title\n';
data.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
console.log(csv);
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'people.csv';
hiddenElement.click();
}
<button onclick="download_csv()">Download CSV</button>

Related

how to overwrite data in html table and export this data to existed excel file

I want to know how to export data in html table to existed excel file. I have found ways to export data to new excel file but what I want is to export this data to an existed excel file.
The code I found to export to new file but again I want to append this data to excel file that I already have.
code:
<script type="text/javascript">
function exportTableToExcel(tableID, filename = 'scenario'){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}

How to export JQGrid in excel with .xlsx format?

I have jqGrid with grouped columns and I want to export jqGrid in excel (.xlsx) format on click of a button.
I am able to export the table in excel with .xls format but this is the old format and I want to export in .xlsx format.
below is the code.
$('#excel').unbind().click(function (){
var a = document.createElement('a');
var data_type = 'data:application/vnd.ms-excel'; ?
var table = $("#hiddenGrid");
var table_html = '<table><thead><style> table, td {border:thin solid lightgrey}</style><tr><th></th><th>Group</th><th>Sort</th><th>Item ID</th><th>Description</th><th>Tag</th><th>Quantity</th><th>Cost Total</th><th>Sell Total</th><th>Qty Shipped</th></tr></thead></table>';
table_html = table_html + table[0].outerHTML;
a.href = data_type + ', ' + escape(table_html).replace("%u", '-');
a.download = 'GridExport.xls';
a.click();
});
I have tried changing GridExport.xls to GridExport.xlsx but no luck.
is there any third-party tool that I have to use to export the excel in .xlsx format? or any other solution?

JS Export HTMLArray to CSV - delimer issue

i have data which i need to export to .csv, for Excel.
I have a function which is working fine but the result file contains all data in first row, in Excel.
Then i need to go to the "Data" tab, then "Text to columns" and pick comma as a delimer.
This is not acceptable.
How can i generate .csv file to avoid this formatting issue ?
I tried \t as a delimer but its not working :/
function download_csv_file(data) {
//define the heading for each row of the data
var csv = 'Header A, Header B, Header C\n';
//merge the data with CSV
data.forEach(function(parentRow) {
parentRow.childNodes.forEach(function(row) {
csv += row.text.concat(',');
});
csv += "\n";
});
//display the created CSV data on the web browser
document.write(csv);
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,\uFEFF' + encodeURIComponent(csv);
hiddenElement.target = '_blank';
//provide the name for the CSV file to be downloaded
hiddenElement.download = 'File_name.csv';
hiddenElement.click();
}
thank in advance for all suggestions

How can I export data from a csv file or excel file to a javascript object?

I would like to know if there is a way to export data from a CSV file to a javascript object and when someone edits the CSV file it automatically changes in the javascript file. Thank you so much.
The following steps are implemented in the below code snippet.Customize this as required.
Select input CSV file. (The code snippet is tested for UTF-8 encoded CSV file)
Read the CSV file data
Parse the CSV file data and contruct the JSON object
Manipulate or modify the JSON object if required.
Export the JSON object as CSV
var CsvRows;
var headers;
// This event will be triggered when file is selected
// Note: This code is tested for UTF-8 encoded CSV file
function handleChange(evt) {
var reader = new FileReader();
reader.onload = function() {
//reader.result gives the file content
document.getElementById('out').innerHTML = reader.result;
//parse the result into javascript object
var lines = reader.result.split('\r\n');
headers = lines[0].split(',');
lines.shift();
CsvRows = lines.map((item) => {
var values = item.split(',');
var row = {};
headers.map((h, i) => {
row[h] = values[i];
});
return row;
});
console.log(CsvRows);
document.getElementById('result').style.display = 'block'
};
//read the selected file
reader.readAsBinaryString(evt.files[0]);
};
//export the javscript object as csv
function exportCSV() {
//contruct the csv ad data url
let csvContent = "data:text/csv;charset=utf-8," +
headers.join(",") + "\r\n";
//contruct the data in csv format
var data = CsvRows.map(e => {
var line = '';
headers.map((h) => {
line += e[h] + ',';
});
return line.substr(0, line.length - 1);
}).join("\r\n")
csvContent += data;
//contruct an anchor tag
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
//provide the export file name
link.setAttribute("download", "mydata.csv");
document.body.appendChild(link); // Required for FF
//trigger download of CSV
link.click();
link.remove();
}
<input type="file" onchange="handleChange(this)" accept=".csv" />
<div id="result" style="display:none;">
<div id="out"></div>
<div>See console for Javascript Object.</div>
<div>Export the imported file <button onclick="exportCSV()">Export</button></div>
</div>
The above code snippet only works for CSV files. Custom implementation has to be made for Excel files.

How to properly export to CSV in JavaScript?

I have a JavaScript function that enables me to download a CVS file. When I open this file in excel, everything is placed in the same column instead.
This is my code:
function convertToCSV(dataArray) {
var csvContent = "data:text/csv;charset=utf-8,";
dataArray.forEach(function(infoArray, index)
{
dataString = infoArray.join(",");
csvContent += index < dataArray.length ? dataString+ "\n" : dataString;
});
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "download.csv");
document.body.appendChild(link);
link.click();
}
This is what it looks like:
This is the output I'm expecting:
What am I doing wrong? Any help would be appreciated.
NB: I have been looking for a way to export straight to an .xlsx or .xls file, but I didn't win.
You can use mongo-xlsx module to export your data to xlsx file
var mongoXlsx = require('mongo-xlsx');
var data=dataArray;
var model=mongoXlsx.buildDynamicModel(data);
mongoXlsx.mongoData2Xlsx(data, model, function(err, data) {
console.log("data",data);
console.log('File saved as:', data.fullPath);
});
Hope this helps
You could do this with native js fairly easily like so:
let text = '';
dataArray.map(arr => text += arr.join(',') + '\r\n');
let link = document.createElement('a');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + escape(text));
link.setAttribute('download', 'download.csv');
document.body.appendChild(link);
link.click();

Categories

Resources