I am actually using this library: https://github.com/SheetJS/js-xlsx.
I used it to create and download an XLSX file that extracts a table from my website. This does work pretty well, but I am trying to do something more complicated now.
I am trying to download all my tables at the same time, which means downloading multiple XLSX files. It does works with my actual code :
function saveAll(dataAll){
for (let i=0;i<dataAll.length;++i) {
let ws_name = "SheetJS";
let data = dataAll[i];
let wb = new Workbook();
console.log(data);
let ws = sheet_from_array_of_arrays(data.content, null, data.mois, data.annee);
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});
saveAs(new Blob([s2ab(wbout)],{type: "application/octet-stream"}), data.prenom_nom + " PVA " + data.mois + " " + data.annee + ".xlsx");
}
}
Now i'd like to download all those xlsx files into an unique ZIP or tar.gz file, but i am kinda stuck. I tryed to use the zip.js library, but without success.
My dataAll parameter is array of objects, and each object contains .content which is a matrix, and some other parameters used on the file name.
How can I manage to download all these xlsx files in only one archive, instead of downloading them one by one?
You can try this
var zip = new JSZip();
for(var i=1;i<3;i++)
{
var workbook = XLSX.utils.book_new();
var ws1 = XLSX.utils.table_to_sheet(document.getElementById('tbl'+i));
XLSX.utils.book_append_sheet(workbook, ws1, "Sheet1");
let wbout = XLSX.write(workbook, {bookType: 'xlsx', bookSST: true, type: 'binary'});
zip.file("shubham"+i+".xlsx", wbout, {binary: true});
}
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "example.zip");
});
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width" , initial-scale=1, shrink>
<meta name="theme-color" content="#000000">
<title>ES6</title>
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.0/jszip.min.js"></script>
</head>
<body>
<table id="tbl1">
<tr><td>Name</td><td>Age</td></tr>
<tr><td>Shubham</td><td>22</td></tr>
</table>
<table id="tbl2">
<tr><td>Name</td><td>Age</td></tr>
<tr><td>Shubham</td><td>22</td></tr>
</table>
</body>
<script>
</script>
</html>
Related
i am currently working on my upload file page and below is the upload function on the client side
and i want the client to check the image first before upload to the server
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Testing</title>
</head>
<body>
<h1>Upload img</h1>
<form action="/upload" method="post" enctype="multipart/form-data" id="form"></form>
<button id="submit" onclick="upload()">Submit</button>
<!-- <script src="main.js"></script> -->
<script>
function multipleImageUpload() {
const input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("multiple", "multiple");
const preview = document.createElement("div");
preview.setAttribute("id", "preview");
document.body.appendChild(preview);
input.addEventListener("change", (event) => {
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
const img = document.createElement("img");
img.setAttribute("src", URL.createObjectURL(files[i]));
const removeBtn = document.createElement("button");
removeBtn.innerHTML = "Remove";
removeBtn.addEventListener("click", () => {
preview.removeChild(img);
preview.removeChild(removeBtn);
});
preview.appendChild(img);
preview.appendChild(removeBtn);
}
});
document.getElementById('form').append(input);
}
multipleImageUpload()
function upload(){
const imgs = preview.querySelectorAll("img");
const files = [];
for (let i = 0; i < imgs.length; i++) {
files.push(imgs[i].src);
}
console.log(files);
//submit
// document.getElementById('form').submit()
}
</script>
</body>
</html>
inside the files is blob file link
how to read these array of blob to behave as File
then inlude it inside my form
when i click sumit these blob file must be submitted too in node server
My Server
var express = require('express');
var router = express.Router();
const multer = require('multer')
const upload = multer({
dest:'uploads/'
})
const cpUpload = upload.fields([{name:'files'}])
router.get('/', function(req, res, next) {
res.render('upload/index');
});
router.post('/', cpUpload,(req, res, next)=>{
console.log(req.files);
})
module.exports = router;
i tried converting to files these blob as new File() method but it didnt work because i have to read the blob as file first to add parameter in new File() even if i input it in the File,
i have to put them in the new FormData()
i dont know how that work
when log the form data theres no values
How Do i debug this in order for me to read and write in json file to html without http request?
I have already got the answer from my previous question project "How to use push() into array json file when "mouse click"?" but now I can't even load/read file from json to html by using my p5.js loadjson project, do i missing something? or do I doing it wrong by arrange my code in the right order?
this is my previous answer project>
How to use push() into array json file when "mouse click"?
my project use for p5.js loadjson>
How to Debug "P5.js + Node.js with Parse Json" file
//my code>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sketch</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="libraries/p5.min.js"></script>
<script src="libraries/p5.sound.min.js"></script>
</head>
<body>
<script src="sketch8.js"></script>
</body>
</html>
sketch8.js
function preload() {
winston = loadJSON("Data2.json");
}
function setup() {
createCanvas(400, 400);
}
function draw() {
//JSON parse & fs read Node.js
// var fs = require('fs');
// var data = fs.readFileSync('Data2.json');
// var winston = JSON.parse(data);
// console.log(winston);
//Test Terminal
/*
node sketch7.js
*/
{
if (mouseIsPressed) {
winston.xPositions.push(mouseX);
} else {
var data = JSON.stringify(winston, null, 2);
fs.writeFileSync('Data2.json', data, finished);
function finished(err) {
console.log('all set.');
}
}
stroke(64, 117, 207);
fill(196, 33, 255);
for (var i = 0; i < winston.xPositions.length; i++) {
line(winston.xPositions[i], 120, 194, 285);
ellipse(winston.xPositions[i], 104, 32, 46);
}
}
fill(0, 0, 0);
textSize(16);
text("Winston likes " + winston.likes[0] + " and " + winston.likes[1], 10, 90);
};//<
Data2.json
{
"likes": ["programming", "being programmed"],
"xPositions": [100, 200]
}
//<my code
After remove the else statement
if I remove the else statement then I can read json file, but that will remove reason to write, I want to "read and write" to json file to html
if (mouseIsPressed) {
winston.xPositions.push(mouseX);
} /*else {
var data = JSON.stringify(winston, null, 2);
fs.writeFileSync('Data2.json', data, finished);
function finished(err) {
console.log('all set.');
}
}
*/ //<else write data to json
The reason i use node without http request cause of this code that I use>
//node code>
app.js
//Create New File 2>>
var fs = require('fs');
fs.readFile('readMe.txt', 'utf8', function(err, data){
fs.writeFile('writeMeMe22.txt', data, function(err, result) {
if(err) console.log('error', err);
});
});
//Terminal
//node app
readMe.txt
ya here???
//<node code
as you can see when i use terminal and type node app or node app.js, It create a new file when read file AKA read and write with node, the new file can also be json file as well, like writeMeMe22.txt > writeMeMe22.json
//new file>
writeMeMe22.txt
ya here???
//<new file
Since sketch8.js is running in a web browser you are not going to be able to use fs.writeFileSync() which is a Node.js function intended for use on the server side. Instead you will want to use saveJSON() to initiate a file download.
In my webpage, I want to download file(ppt, pdf, xlsx) when I click <a/> tag.
I used a tag with download attribute, but in IE it doesn't work.
So I referred to here (Download attribute on A tag not working in IE
), and now download works in IE but the file is not opened. I tried .xlsx file and when I open it, it says that
contents have problem.
How can I download and open my .xlsx .pdf .ppt file in IE with javascript?
I'm a beginner web programmer and I need some advice from a good developer like you.
Thanks in advance.
this is my code
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<a id='a1' href="https://image.shutterstock.com/image-photo/colorful-flower-on-dark-tropical-260nw-721703848.jpg"
download>excel</a>
<script>
function MS_bindDownload(el) {
if (el === undefined) {
throw Error('I need element parameter.');
}
if (el.href === '') {
throw Error('The element has no href value.');
}
var filename = el.getAttribute('download');
console.log("filename : " ,filename);
if (filename === null){
throw Error('I need download property.');
}
if (filename === '') {
var tmp = el.href.split('/');
filename = tmp[tmp.length - 1];
}
el.addEventListener('click', function (evt) {
evt.preventDefault();
var xhr = new XMLHttpRequest();
xhr.onloadstart = function () {
xhr.responseType = 'blob';
};
xhr.onload = function () {
navigator.msSaveBlob(xhr.response, filename);
};
xhr.open("GET", el.href, true);
xhr.send();
})
}
let element = document.querySelector('a');
MS_bindDownload(element);
</script>
</body>
</html>
I have uploaded files (Docx, PDF, JPG) on S3 and I want to fetch the file from S3 and render it on webpage without downloading the content.
Index.js
var AWS = require('aws-sdk');
var btoa = require('btoa');
AWS.config.update(
{
accessKeyId: "accessKeyId",
secretAccessKey: "secretAccessKey"
}
);
var s3 = new AWS.S3();
s3.getObject(
{ Bucket: "bucket", Key: "test.PDF" },
function (error, data) {
if (error != null) {
console.log("Failed to retrieve an object: " + error);
} else {
var Base64 = require('js-base64').Base64;
var b = Base64.encode(data.Body);
var fileToView = "data:image/jpeg;base64," + b;
res.render('index', { title: '' , pdfVal: fileToView });
}
}
);
index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1Welcome <%= title %></h1>
</body>
</html>
I want to render the PDF or any file type to view it on page without downloading it from Amazon S3.
I am not able to view the file even after appending content type to the byte.
I tried to follow few stack overflow questions as well but it didn't help.Can someone help me with this? or a link to previous Stackoverflow questions will help too.
So I am trying to use the SheetJS javascript to read in some excel files. I download the SheetJS and I have copied the xlsx.full.min.js in same directory as my html file. However, I do not get it to work. So I tried the code below. The problem is that it does not reach the alert('finished reading'); line. So I do not know if there was a problem reading the source file or what the problem exactly is. I hope somebody can help me with this! Thanks!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
</style>
</head>
<body>
<p><input type="file" name="xlfile" id="xlf" /> ... or click here to select a file</p>
<script src="xlsx.full.min.js"></script>
<script>
function handleFile(e) {
//Get the files from Upload control
var files = e.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
alert(data);
var result;
alert('reading now');
var workbook = XLSX.read(data, { type: 'binary' });
alert('finished reading');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
if (roa.length > 0) {
result = roa;
}
});
//Get the first column first cell value
alert(result[0].Column1);
};
reader.readAsArrayBuffer(f);
}
}
var xlf = document.getElementById('xlf');
if(xlf.addEventListener) xlf.addEventListener('change', handleFile, false);
</script>
</body>
</html>