Save options from a select to file with JS - javascript

Hello I have a select and an input button to browse files, and i would love to save the options in the select to a text file in the format:
line1
line2
line3
...
I have read this tutorial:
Save <Select >Tag values into text file
But it does not seem to work. When i save, the options are written in the same line and only the first word for the option value is writte to the file.
I.E. my options are:
buy food
call john
print documents
the output in the file is:
buy call print
The code i use is:
var textToWrite = "";
$('#todolist>option').each(function () {
textToWrite += this.value + "\n";
});
var textFileAsBlob = new Blob([textToWrite], {type: 'text/plain'});
var fileNameToSaveAs = "directive.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
console.log("innerHTML -> " + downloadLink.innerHTML);
window.webkitURL != null;
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
downloadLink.click();
}
var button = document.getElementById('file-save');
button.addEventListener('click', saveTextAsFile);
I am using google's link for jquery:
Can anybody help? Thanks in advance

So you want also the text, not only the values?
$('#todolist>option').each(function () {
textToWrite += this.value + "\n" + this.innerText + "\n";
});

Related

Download HTML table to Excel by using Javascript

In my Flask application, I created a button to extract the content of an HTML table into an Excel file. I used Javascript to extract from my interface the content of my HTML table in Excel format.
Unfortunately, when I run the code below, the downloaded Excel file is empty. Could you please help to correct my code below. Thanks.
function exportTableToExcel(filename = ''){
let downloadLink;
let dataType = 'application/vnd.ms-excel';
let tableSelect = document.getElementsByTagName("table");
let tableHTML = tableSelect[0].outerHTML.replace(/ /g, '%20');
// Specify file name
filename = 'All_Issues.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();
}
}
The getElementsByTagName() function returns an array so you have to get the first element.
let tableHTML = tableSelect[0].outerHTML.replace(/ /g, '%20');

Blob creating function in javascript saving multiple files

Can someone explain to me how this piece of code works. Also, the output is not what I want. It saves 2 files instead of 1.
Javascript
function saveTextAsFile() {
var textToWrite = document.getElementById('textArea').innerHTML;
var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
var fileNameToSaveAs = "file.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null) {
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);
function destroyClickedElement(event) {
document.body.removeChild(event.target);
}
HTML
<button id="save" onclick="saveTextAsFile()">Save</button>
<textarea id="textArea" class="Textarea" placeholder="Click to Type" cols="20"></textarea>
You code does NOT work:
textarea input values are read with .value not .innerHTML, you where getting no output so
change:
var textToWrite = document.getElementById('textArea').innerHTML;
into
var textToWrite = document.getElementById('textArea').value;
You get 2 files because you made 2 same events on same button that call same function, remove one of those:
<button id="save" onclick="saveTextAsFile()">Save</button>
here remove onclick="saveTextAsFile()" or remove this two lines:
var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);
This will fix your errors, and as far how whole code works, this is not code review site, for that visit https://codereview.stackexchange.com/ or google each command and read its definitions.

How to create a txt file from a string with exactly whats what is in the string?

I have created a simple HTML file that has a textarea, two text input, and a button that when the button is clicked it downloads what is in the textarea with what is in the text input as the name. This has worked for me a very long time until I typed text with a #. When I put the # it would create the txt file with only the stuff before the #. This is the code for how I download it.
function generate() {
var textToSave = document.getElementById('Input1').value;
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = document.getElementById('fileName').value+'.' + document.getElementById("fileExtension").value;
hiddenElement.click();
}
I can't use anything but the #, so I need a way for the file to keep all the text.
You should try with a blob :
var textToSave = document.getElementById('Input1').value;
var hiddenElement = document.createElement('a');
hiddenElement.download = 'string.txt';
var blob = new Blob([textToSave], {
type: 'text/plain'
});
hiddenElement.href = window.URL.createObjectURL(blob);
hiddenElement.click();

Export 2D javascript array to Excel sheet

I know, there are hundreds of questions on this topic on here, but I still could not find satisfactory answers after a day of searching:
I have a 2D javascript array, which I want to download as an Excel sheet.
Here is a fiddle with the code I got so far:
https://jsfiddle.net/3an24jmw/7/
The download works, but there are several issues, which I could not solve after days of trying:
All items end up in the first column of the Excel sheet, because Excel interprets the "," separating the elements as part of the data. How can I separate the elements in a way Excel understands?
The file name is some cryptic code. How can I set the file name?
The downloaded file has a double .xls ending (.xls.xls). How can get a single .xls ending?
Excel tells me every time the file could be corrupted or unsafe. How do I prevent this?
Any help for any of these questions would be appreciated.
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "\r\n";
});
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(CsvString));
}
UPDATE
I just found out by chance, that 1. 2. and 4. can be solved by replacing vnd.ms-excel with csv.
The file will not be .xls anymore, but the csv can be opened by Excel without problems and behaves like intended.
Only problem remaining is the file name!
UPDATE 2
Finally after 2 full workdays of searching and trying, I found the solution, which I would like to share here, to help anybody with the same problem:
Simply include an invisible <a> element, which defines the file an useful name using its download="somedata.csv" attribute.
Here is my final and fully functional fiddle:
https://jsfiddle.net/3an24jmw/25/
Finaly after 2 full workdays of searching and trying, I found the solution, which I would like to share here, to help anybody with the same problem:
Simply include an invisible element, which gives the file an usefull name using its download="somedata.csv" attribute:
Here is my final and fully functional fiddle:
https://jsfiddle.net/3an24jmw/25/
var Results = [
["Col1", "Col2", "Col3", "Col4"],
["Data", 50, 100, 500],
["Data", -100, 20, 100],
];
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "\r\n";
});
CsvString = "data:application/csv," + encodeURIComponent(CsvString);
var x = document.createElement("A");
x.setAttribute("href", CsvString );
x.setAttribute("download","somedata.csv");
document.body.appendChild(x);
x.click();
}
The separator Excel expects for csv depends on your system locale setting for list separator.
You can hint Excel which separator to use for your csv file by adding "sep=," as the first line.
In your case use could use: var CsvString = '"sep=,"\r\n';
https://github.com/shuchkin/simplexlsxgen#js-array-to-excel-ajax
<?php // array2excel.php
if (isset($_POST['array2excel'])) {
require __DIR__.'/simplexlsxgen/src/SimpleXLSXGen.php';
$data = json_decode($_POST['array2excel'], false);
\Shuchkin\SimpleXLSXGen::fromArray($data)->downloadAs('file.xlsx');
return;
}
?>
<html lang="en">
<head>
<title>JS array to Excel</title>
</head>
<script>
function array2excel() {
var books = [
["ISBN", "title", "author", "publisher", "ctry"],
[618260307, "The Hobbit", "J. R. R. Tolkien", "Houghton Mifflin", "USA"],
[908606664, "Slinky Malinki", "Lynley Dodd", "Mallinson Rendel", "NZ"]
];
var json = JSON.stringify(books);
var request = new XMLHttpRequest();
request.onload = function () {
if (this.status === 200) {
var file = new Blob([this.response], {type: this.getResponseHeader('Content-Type')});
var fileURL = URL.createObjectURL(file);
var filename = "", m;
var disposition = this.getResponseHeader('Content-Disposition');
if (disposition && (m = /"([^"]+)"/.exec(disposition)) !== null) {
filename = m[1];
}
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = fileURL;
} else {
a.href = fileURL;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
alert("Error: " + this.status + " " + this.statusText);
}
}
request.open('POST', "array2excel.php");
request.responseType = "blob";
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("array2excel=" + encodeURIComponent(json));
}
</script>
<body>
<input type="button" onclick="array2excel()" value="array2excel" />
</body>
</html>

Export contents inside <div> as a .docx File

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);
}

Categories

Resources