Export 2D javascript array to Excel sheet - javascript

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>

Related

Save options from a select to file with JS

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

How to write data in JSON file in the EJS template file [duplicate]

I want to Write Data to existing file using JavaScript.
I don't want to print it on console.
I want to Actually Write data to abc.txt.
I read many answered question but every where they are printing on console.
at some place they have given code but its not working.
So please can any one help me How to actually write data to File.
I referred the code but its not working:
its giving error:
Uncaught TypeError: Illegal constructor
on chrome and
SecurityError: The operation is insecure.
on Mozilla
var f = "sometextfile.txt";
writeTextFile(f, "Spoon")
writeTextFile(f, "Cheese monkey")
writeTextFile(f, "Onion")
function writeTextFile(afilename, output)
{
var txtFile =new File(afilename);
txtFile.writeln(output);
txtFile.close();
}
So can we actually write data to file using only Javascript or NOT?
You can create files in browser using Blob and URL.createObjectURL. All recent browsers support this.
You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though.
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an example that uses this technique to save arbitrary text from a textarea.
If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique.
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
Some suggestions for this -
If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
To store some information on the client side that is considerably small, you can go for cookies.
Using the HTML5 API for Local Storage.
If you are talking about browser javascript, you can not write data directly to local file for security reason. HTML 5 new API can only allow you to read files.
But if you want to write data, and enable user to download as a file to local. the following code works:
function download(strData, strFileName, strMimeType) {
var D = document,
A = arguments,
a = D.createElement("a"),
d = A[0],
n = A[1],
t = A[2] || "text/plain";
//build download link:
a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);
if (window.MSBlobBuilder) { // IE10
var bb = new MSBlobBuilder();
bb.append(strData);
return navigator.msSaveBlob(bb, strFileName);
} /* end if(window.MSBlobBuilder) */
if ('download' in a) { //FF20, CH19
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
}; /* end if('download' in a) */
//do iframe dataURL download: (older W3)
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
}
to use it:
download('the content of the file', 'filename.txt', 'text/plain');
Try
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
If you want to download binary data look here
Update
2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here
Above answer is useful but, I found code which helps you to download text file directly on button click.
In this code you can also change filename as you wish. It's pure javascript function with HTML5.
Works for me!
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN to provide extra parameters for file type. By default it will make .txt file
In the case it is not possibile to use the new Blob solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:
function download() {
var fileContents=JSON.stringify(jsonObject, null, 2);
var fileName= "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {download()}, 500);
$('#download').on("click", function() {
function download() {
var jsonObject = {
"name": "John",
"age": 31,
"city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {
download()
}, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="download">Download me</button>
Use the code by the user #useless-code above (https://stackoverflow.com/a/21016088/327386) to generate the file.
If you want to download the file automatically, pass the textFile that was just generated to this function:
var downloadFile = function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
}
I found good answers here, but also found a simpler way.
The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)
You can style the link as a button using bootstrap, which is still pure javascript, except for styling.
Combining the button and the download link also reduces code, as fewer of those ugly getElementById calls are needed.
This example needs only one button click to create the text-blob and download it:
<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary"
onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
Write To File
</a>
<script>
// URL pointing to the Blob with the file contents
var objUrl = null;
// create the blob with file content, and attach the URL to the downloadlink;
// NB: link must have the download attribute
// this method can go to your library
function exportFile(fileContent, downloadLinkId) {
// revoke the old object URL to avoid memory leaks.
if (objUrl !== null) {
window.URL.revokeObjectURL(objUrl);
}
// create the object that contains the file data and that can be referred to with a URL
var data = new Blob([fileContent], { type: 'text/plain' });
objUrl = window.URL.createObjectURL(data);
// attach the object to the download link (styled as button)
var downloadLinkButton = document.getElementById(downloadLinkId);
downloadLinkButton.href = objUrl;
};
</script>
Here is a single-page local-file version for use when you need the extra processing functionality of a scripting language.
Save the code below to a text file
Change the file extension from '.txt' to '.html'
Right-click > Open With... > notepad
Program word processing as needed, then save
Double-click html file to open in default browser
Result will be previewed in the black box, click download to get the resulting text file
Code:
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
// do text manipulation here
let string1 = 'test\r\n';
let string2 = 'export.';
// assemble final string
const finalText = string1 + string2;
// convert to blob
const data = new Blob([finalText], {type: 'text/plain'});
// create file link
const link = document.createElement('a');
link.innerHTML = 'download';
link.setAttribute('download', 'data.txt');
link.href = window.URL.createObjectURL(data);
document.body.appendChild(link);
// preview the output in a paragraph
const htmlBreak = string => {
return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
}
const preview = document.createElement('p');
preview.innerHTML = htmlBreak(finalText);
preview.style.border = "1px solid black";
document.body.appendChild(preview);
</SCRIPT>
</BODY>
</HTML>

how to load data using a javascript

I have almost zero experience with Javascript , I need to use this Javascript in my php script .
<script>
let arr = ["alfa", "beta", "charlie"]
const updateResult = query => {
let resultList = document.querySelector(".result");
resultList.innerHTML = "";
arr.map(algo =>{
query.split(" ").map(word =>{
if(algo.toLowerCase().indexOf(word.toLowerCase()) != -1){
resultList.innerHTML += `<li class="list-group-item">${algo}</li>`;
}
})
})
}
updateResult("")
</script>
This script load the data using
let arr =
However suppose I have all the data specified there in a file in this format
c:/data/mydata.txt
and the data.txt contains data in this form (one data per row)
alfa
bravo
charlie
Now how should I change the javascript above to load the data from c:/data/mydata.txt and not using
let arr = ["alfa", "beta", "charlie"]
?
Thank you
You do not need to change your file, but you cannot use it directly due to security issues. If I would write a Javascript which reads your secret files and you load my page, all your secrets would be revealed, therefore, if you want to load a file, you either have to allow your user to upload it and once the user uploads the file do your logic, or, you can request it via AJAX.
How to upload a file
An example for this is
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<p id="demo"></p>
<script>
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += "<br><strong>" + (i+1) + ". file</strong><br>";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
</script>
<p><strong>Tip:</strong> Use the Control or the Shift key to select multiple files.</p>
</body>
</html>
source: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
Getting the file via AJAX
In order to do that, you will need to:
send an AJAX request in your javascript code
parse the request and send back the file via PHP
do your logic in Javascript when the request is responded
Example:
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Download POST Request</title>
</head>
<body>
Enter a text and click the button: <input type="text" id="content" value="Text for the generated pdf">
<button id="download">Send AJAX Request and download file</button>
<script>
document.getElementById('download').addEventListener('click', function () {
var content = document.getElementById('content').value;
var request = new XMLHttpRequest();
request.open('POST', '../server/', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function() {
// Only handle status code 200
if(request.status === 200) {
// Try to find out the filename from the content disposition `filename` value
var disposition = request.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
// The actual download
var blob = new Blob([request.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// some error handling should be done here...
};
request.send('content=' + content);
});
</script>
</body>
</html>
PHP
<?php
require_once 'vendor/autoload.php';
if($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-type: application/pdf');
http_response_code(200);
// Contents
$pdfContent = !empty($_POST['content']) ? $_POST['content'] : 'no content specified';
// Generate the PDOF
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10, $pdfContent);
return $pdf->Output(null, 'foobar-' . time() . '.pdf');
}
// Bad method
http_response_code(405);
exit();
Source: https://nehalist.io/downloading-files-from-post-requests/
You will of course need to modify the code to comply to your needs. Reading a tutorial would not hurt.
you can use ajax for loading data from external file.
a sample of jquery get call is given below. You can also use the same code with your file path and variables.
$("button").click(function(){
$.get("demo_test.php", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
if you are using pure java script instead of jQuery you have to use pure ajax calls.
for more details about jQuery ajax check this link

Trying to create and download thousands of files not working now

Ok so I wrote this program to avoid having to manually reformat several >6000 entry csv files by hand. It froze on the first run of the full file, then ran fine when i gave it a 1000 entry chunk i got 1000 files in my downloads folder. Now it won't download more than 51 at a time. The rest are converted to my XML format but they don't automatically download.
<script src="./papaparse.min.js"></script>
<script src="./jquery-2.2.1.min.js"></script>
<script>
var data;
var j = 1001;
function handleFileSelect(evt) {
var file = evt.target.files[0];
Papa.parse(file, {
header: true,
dynamicTyping: false,
// preview: 5,
step: function(results, parser) {
j++
// console.log("Row data:", results.data);
// console.log("Row errors:", results.errors);
// $("#test").text(results.data["0"]["correct_answer"]);
var dataArray = [j,
results.data["0"]["question_id"],
results.data["0"]["node_id"],
results.data["0"]["part_text"],
results.data["0"]["distractor_1"],
results.data["0"]["distractor_2"],
results.data["0"]["distractor_3"],
results.data["0"]["correct_answer"],
results.data["0"]["explanation"]];
dataArray = HTMLGunkCleanse(dataArray);
XMLWriter(dataArray[0],
dataArray[1],
dataArray[2],
dataArray[3],
dataArray[4],
dataArray[5],
dataArray[6],
dataArray[7],
dataArray[8]);
}//end of the line for stuff to do with each iteration of data
})
};
function HTMLGunkCleanse(dataArray){
var regex = /<[^>]*>/g;
for (i = 3;i<8;i++){
dataArray[i] = dataArray[i].replace("<p>", "\r\n").replace("</p>", "").trim();
var check = dataArray[i];
dataArray[i] = dataArray[i].replace(regex, "").replace("\\s+", "").trim();
if (check != dataArray[i]){
console.log(check);
console.log(dataArray[i]); // shows any differences that may have occured
}
}
return dataArray
}
function XMLWriter(fileName, qID, nodeID, question, d1, d2, d3, correct, feedback){
setTimeout(function(){console.log("waiting");},1)
//create long ugly string that looks good in xml
var blob = new Blob([doc.toString()], {
type: "text/plain;charset=utf-8"
});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "cfal_question_00006_" + fileName + ".dita";
a.href = url;
a.textContent = "Download latest";
a.click();
//if the click() function dosen't work you can try using onclick() fucntion like this
//a.onclick();
document.getElementById('test').appendChild(a);
}
$(document).ready(function(){
$("#csv-file").change(handleFileSelect);
});
</script>
<input type="file" id="csv-file" name="files"/>
<div id="test">
</div>
In preresponse to question yes i realize its ugly. I've taken one javascript class and don't some stuff online so i'm kinda newish. Any advice on why it was working fine and doesn't work now? I am using Google chrome to run it btw.
In your function 'HTMLGunkCleanse', return dataArray doesn't end with a ';' Maybe that's the problem?

How to support "\n" when exporting csv file with javascript

I am trying to export an array data to a csv file, which works fine unless it has break line("\n"). I hope to make it support break line in a single cell, is it possible?
I tried replace \n into "\n" or "'\n'" but it does not work
The function I am using:
function arrayToCSVConvertor(arrData, ReportTitle) {
var CSV='';
arrData.forEach(function(infoArray, index){
var dataString = infoArray.join(",");
//dataString= dataString.split('\n').join('\\n');//Here, need something to suport "\n"
CSV += dataString+ "\n";
});
if (CSV == '') {
alert("Invalid data");
return;
}
//create a link and click then remove
var link = document.createElement("a");
link.id="lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var csv = CSV;
/* window.open(encodeURI(csv));*/
var blob = new Blob([csv], { type: 'text/csv' });
//var csvUrl = window.webkitURL.createObjectURL(blob);
var csvUrl = createObjectURL(blob);
var filename = ReportTitle+'.csv';
if(navigator.msSaveBlob){//IE 10
return navigator.msSaveBlob(blob, filename);
}else{
$("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
$('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
}
PS: I have Chinese words inside the array
I suggest avoiding the pain of working with CSV directly and all it's little variants and just use some library like Papa Parse to handle the job for you.
Basically, the new line to be used within a value should be a \n and the new line to end a record should be \r\n but as #user2864740 commented the results vary based on the encoding of the file and where you are going to open it.

Categories

Resources