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
Related
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?
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>
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.
I have successfully exported my data as csv which worked great until there is a # character which messed up the exporting. It stopped the exporting anything after #. When I open the file, I can see that it's giving a newline then stopped.
I already added quotations to the text fields because of the need to export symbols such as , which works fine.
Can someone give me suggestions of why meeting # would give such reaction and way to solve it?
removing # is the least option to think of, would really prefer to keep the # I tried replacing # as ascii \u0023 which gives me no luck
How I get the text
const getDiv = bodyCellLabelClass.querySelectorAll('div');
const innerTxt = getDiv[ 0 ].innerText;
result.push(`"${innerTxt}"`);
sample of result would look like if I console.log
[""$41.67"", ""9/9/2018"", ""10/9/2018"", ""9/9/2018"", ""#111"", ""3/11/2019""]
[""$41.67"", ""9/9/2018"", ""10/9/2018"", ""9/9/2018"", ""3"", ""3/11/2019""]
but when I open the csv it'll look like
$41.67, 9/9/2018, 10/9/2018, 9/9/2018, '↵' nothing after
this is how the export csv looks like
export class ExportUtil {
// export file, default excel
public static spreadsheet( rows, full_filename = 'test.xls' ): any {
let content = `data:application/vnd.ms-excel;charset=utf-8;`;
rows.forEach(function ( rowArray ) {
const row = rowArray.join(',');
content += row + '\r\n';
});
console.log(content, 'inside spreadsheet content');
const encodedUri = encodeURI(content);
const link = document.createElement('a');
link.setAttribute('href', encodedUri);
link.setAttribute('download', `${full_filename}`);
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "my_data.csv".
}
}
Thanks in advance for any help and suggestions.
try using Blob
export class ExportUtil {
// export file, default excel
public static spreadsheet( rows, full_filename = 'test.xls' ): any {
let content = '';
rows.forEach(function ( rowArray ) {
const row = rowArray.join(',');
content += row + '\r\n';
});
console.log(content, 'inside spreadsheet content');
const blob = new Blob([ content ], { type: 'application/vnd.ms-excel;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', `${full_filename}`);
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "my_data.csv".
}
}
I have this ExtJS code which is for converting a grid data into Excel format and write to a file, the code will ultimately export the grid data into downloadable Excel file. This works great in firefox and chrome but fails to function in IE browser (IE 11).
on analyzing found that the code will ultimately post below string onto URL box which will download the excel file.
data:application/vnd.ms-excel;base64,<base64 encoded string follows here>
at first, I thought problem might be somewhere in the code, then i happen to check below steps.
if i paste below content either in chrome or firefox, it prompts for file download and downloads a dummy file.
data:application/vnd.ms-excel;base64,blahblahblahblahblah
however if i paste the above same string in IE 11, it does nothing. So i am on the assumption that code is working fine but i may have to do something more to make it compatible for IE browser. But i dont know what else i could try.
any pointer is deeply appreciated.
below is my ExtJS code, if it helps.
//here xmlString has the constructed xml string which holds
//grid column headers + grid rows with Table, Column, Cell and Worksheet tags.
var ctx = {
created : (new Date()).getTime(),
worksheets : xmlString
};
var uri = 'data:application/vnd.ms-excel;base64,',
tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">' + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>BlahBlah</Author><Created>{created}</Created></DocumentProperties>' + '<Styles>' + '<Style ss:ID="columnHeader"><Font ss:Size="11" ss:Bold="1" /><Interior ss:Color="#CCFFCC" ss:Pattern="Solid"/> </Style>' + '</Styles>' + '{worksheets}</Workbook>',
base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)));
},
format = function(s, c) {
return s.replace(/{(\w+)}/g, function(m, p) {
return c[p];
});
};
var workbookXML = format(tmplWorkbookXML, ctx);
var link = document.createElement("A");
link.href = uri + base64(workbookXML);
link.download = sheetName + " Level Report - " + Ext.Date.format(new Date(), 'Y-m-d H:i:s') + '.xls';
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
PS: I have tried this on both ExtJS V4.1 and V6.0 but same behaviour.