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".
}
}
Related
The line in question looks like this:
LongWord (Word Word 7) - Word - +55555555
And when it's imported it looks like this:
LongWord (Word Word 7) - Word - +55555555
The .csv file is generated in the browser using .js:
/**
* Generate CSV file in browser and download
*/
function download(csv) {
// CSV File
var csvFile = new Blob([csv], { type: 'text/csv' })
// Download link
var downloadLink = document.createElement('a')
// File name
downloadLink.download = self.filename
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile)
// Make sure that the link is not displayed
downloadLink.style.display = 'none'
// Add the link to your DOM and click
document.body.appendChild(downloadLink)
downloadLink.click()
}
I can't find other examples online of this happening nor can I debug it.
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
Here What I am trying to do but not able to achieve the result.The data is getting downloaded without the '.csv' extension.
function get_modal1(data) {
$("#popupcontent").html(data);
var t = document.getElementById('tablename').innerText;
$('title').html(t);
$('#example').DataTable({
dom: 'lBfrtip',
buttons: [
'csv',
]
} );
this is how the data table is get exported without the extension .csv
I am not able to export the data as .csv. What I am doing wrong here?
The data is getting downloaded and when I open it with notepad it is comma separated.What could be the problem here?
[1]:
It's a bit of a rewrite but this is what I'd do, assuming your function is what will format the data and cause the file download:
function get_modal1(_data) {
// create a blob in memory of type text/csv
var _blob = new Blob([_data], {type: 'text/csv'});
var _file = "my_data.csv";
// create an anchor in memory for the file
var anc = document.createElement('a');
anc.style = "display: none";
// populate the url with the blob
var _f_url = window.URL.createObjectURL(blob);
anc.href = _f_url;
anc.download = _file;
// In case you have to support IE 11, IE 11 cannot handle dynamic click of an anchor to initiate save, so use msSaveBlob instead.
// in any case, fire the anchor link just created... user should get the file at this point.
if ( window.navigator.msSaveBlob ) {
window.navigator.msSaveBlob(blob, _file);
} else {
anc.dispatchEvent(new MouseEvent('click'));
}
// clear url out of memory to be safe.
window.URL.revokeObjectURL(_f_url);
});
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 am having trouble exporting the contents of a div into a .docx file. I am using FileSaver.js which can be found here: https://github.com/eligrey/FileSaver.js/.
My JavaScript Function:
function exportNote(){
var blob = new Blob([document.getElementById('editor').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8"
});
saveAs(blob, "note.docx");
}
I get a download that appears to be a word file but when I open it I get the following error:
The Open XML file note.docx cannot be opened because
there are problems with the contents or the file name
might contain invalid characters (for example. /).
Details:
The file is corrupt and cannot be opened.
For graphical purposes:
The text area is the area I am trying to export into a word document which is under <div id="editor"></div>.
jsfiddle
Html
<div id="main">
this is content of div
</div>
JavaScript
function downloadInnerHtml(filename, elId) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + 'text/doc' + ';charset=utf-8,' + encodeURIComponent(elHtml));
link.click();
}
var fileName = 'tags.doc'; // You can use the .txt extension if you want
downloadInnerHtml(fileName, 'main');
There is another solution to this problem using an open source library on github under the MIT license: https://github.com/evidenceprime/html-docx-js.
My solution:
function exportNote(contentId){
var filename = 'note.html'
var htmlDoc = document.getElementById(contentId).innerHTML;
var converted = htmlDocx.asBlob(htmlDoc);
saveAs(converted, "notes.docx");
}
Since somebody had a problem in the comments, I'm pasting in what I am actively using. The function I pasted here is darn near verbatim from this site: https://www.codexworld.com/export-html-to-word-doc-docx-using-javascript/
So credit to them. The key to this is that saving the contents of a div to a file is not a proper HTML document, and that causes Word to balk. It needs a BODY, HTML and some of that xmlns attributing. This function gets the innerHtml and wraps it with that, before doing the actual save.
Simply call Export2Word() with the name of the element that holds the content you want to save and the filename:
Export2Word('divMyContent','MyFileNameWithoutExtension');
function Export2Word(element, filename = ''){
var preHtml = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
var postHtml = "</body></html>";
var content = document.getElementById(element).innerHTML;
var html = preHtml+content+postHtml;
var blob = new Blob(['\ufeff', html], {
type: 'application/msword'
});
// Specify link url
var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);
// Specify file name
filename = filename?filename+'.docx':'document.docx';
// Create download link element
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob ){
navigator.msSaveOrOpenBlob(blob, filename);
}else{
// Create a link to the file
downloadLink.href = url;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
document.body.removeChild(downloadLink);
}