Welcome folks today in this blog post we will be exporting raw json
to excel
file using json2xls
library in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below commands as shown below
npm init -y
npm i express
npm i json2xls
And after that you will see the directory structure
of the node.js express app as shown below
And now you need to make the index.js
file which will be the starting point of the application as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 |
const express = require('express'); const app = express(); const json2xls = require('json2xls'); const bodyparser = require('body-parser') app.use(bodyparser.json()) app.use(bodyparser.urlencoded({extended:false})) app.use(json2xls.middleware); app.listen(3000, () => { console.log('Server started on port 3000'); }); |
As you can see we are importing the express
and json2xls
libraries at the very top and starting a very basic express
app at port number 3000. And also we are applying the middleware of bodyparser
and json2xls
to the express app.
1 2 3 |
app.get('/',(req,res) => { res.sendFile(__dirname + "/index.html") }) |
As you can see we have a simple get
route for the express app in which we are loading the index.html
file when we open the /
route of the express app. Now we need to make the index.html
template which will contain the simple html5
form where we allow the user to enter the raw json
and a simple button to submit the form.
index.html
1 2 3 4 5 |
<form action="/download" method="post"> <textarea type="text" name="json" cols="30" rows="5" placeholder="Enter JSON here" required></textarea> <br> <button type="submit">Download Excel</button> </form> |
Now we need to write the /download
post request where we get the json
data submitted by the user and then we use the json2xls
library to export the raw json
to excel and download it inside the browser as an attachment.
1 2 3 4 5 6 |
app.post('/download', (req, res) => { let data = req.body.json console.log(data) res.xls('data.xlsx', JSON.parse(data)); }); |
As you can see in the above post
request we are firstly of parsing the json
using JSON.parse()
method and then passing that to the res.xls()
to download the output as an data.xlsx
file as attachment in the browser.
FULL SOURCE CODE
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
const express = require('express'); const app = express(); const json2xls = require('json2xls'); const bodyparser = require('body-parser') app.use(bodyparser.json()) app.use(bodyparser.urlencoded({extended:false})) app.use(json2xls.middleware); app.get('/',(req,res) => { res.sendFile(__dirname + "/index.html") }) app.post('/download', (req, res) => { let data = req.body.json console.log(data) res.xls('data.xlsx', JSON.parse(data)); }); app.listen(3000, () => { console.log('Server started on port 3000'); }); |