3

Hi i am new to MEAN Stack.

I want to download the excel file when i click the export button.

I am using this reference link to download the excel file :https://www.npmjs.com/package/exceljs

Html Page

<button ng-click="exportData()" class="btn btn-sm btn-primary btn-create">Export</button>

my controller

var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies", "ngRoute"]);
        app.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
        }]);

app.controller('ManageMaterialFlowController', ['$http', '$scope', '$window', '$filter', '$notify', '$cookieStore',  'StoreService',
 function ($http, $scope, $window, $filter, $notify, $cookieStore, StoreService, $routeProvider) {



     //download excel file button click

     $scope.exportData = function () {

         router.get('/download', function (req, res) {

             try {
                 var Excel = require('exceljs');
                 var workbook = new Excel.Workbook();
                 var options = {
                     filename: './Excel.xlsx',
                     useStyles: true,
                     useSharedStrings: true
                 };
                 var workbook = new Excel.Workbook();
                 var worksheet = workbook.addWorksheet('My Sheet');

                 worksheet.columns = [
                     { header: 'Id', key: 'id', width: 10 },
                     { header: 'Name', key: 'name', width: 32 },
                     { header: 'D.O.B.', key: 'DOB', width: 10 }
                 ];
                 worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) });
                 worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) });

                 var tempFilePath = tempfile('.xlsx');
                 workbook.xlsx.writeFile(tempFilePath).then(function () {
                     console.log('file is written');
                     res.sendFile(tempFilePath, function (err) {
                         console.log('---------- error downloading file: ' + err);
                     });
                 });
             } catch (err) {
                 console.log('OOOOOOO this is the error: ' + err);
             }

         });

     };
}

I don't know how to do this. is this is correct to way to download the excel file by clicking the button.

when I click the button i getting router is not defined error. Can any one solve my issue.

Vinoth
  • 972
  • 1
  • 16
  • 47
  • Hi, You have added your server code in client side(AngularJS), you can refer [Express.js](https://expressjs.com/) for your Node.js (here you can set url's using express.Router()) development and for your client side file download refer [here](https://jsfiddle.net/esy4kLm2/5/) – Kanagu Jun 09 '17 at 09:20
  • For your server code you can use the same code that you have right now and store in a folder, then for download you can refer [here](https://stackoverflow.com/questions/7288814/download-a-file-from-nodejs-server-using-express) – Kanagu Jun 09 '17 at 09:27
  • Hi Kanagu, in your fiddle link not display anything.( Express.js ) nothing is there. Before i have tried like this can you refer this link https://stackoverflow.com/questions/44369082/excel-download-is-not-working-in-mean-stack-app?noredirect=1#comment75820326_44369082 – Vinoth Jun 09 '17 at 12:47
  • what is the definition of `exportData()` function? – Rupali Jun 09 '17 at 17:07
  • Hi rupali, exportData() is ng-click function.if i click the button it will download the excel file – Vinoth Jun 12 '17 at 05:45
  • @Vinoth I think you are confused between the node.js code and angular code. The controller is a .js file. You have directly copied the code for excel without understanding what it does. The router is a variable of express router. var express = require('express'); var router = express.Router(); – codeinprogress Jun 12 '17 at 10:50
  • Hi code in progress, i have created my file i don't know how to download the file can you give me some example – Vinoth Jun 12 '17 at 13:34

2 Answers2

2

Do not use

workbook.xlsx.writeFile()

writeFile() method is for saving file to hard disk.

Instead, use write() method. This method writes file to a stream.

res object is a Writable stream. So you can use like this.

workbook.xlsx.write(res)

and you don't need to call

res.sendFile(tempFilePath) 

Because you already piplined excel file to res object. So code is like this

workbook.xlsx.write(res).then(function () {
    res.status(200).end();
});

Finally, You should add https headers on res object.

res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

res.setHeader("Content-Disposition", "attachment; filename=YOUR_FILENAME.xlsx");

Content-Type notify Web Browser that what data type is.

Content-Disposition notify Web Browser that this data will be saved to hard disk.

Final code is here.


res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

res.setHeader("Content-Disposition", "attachment; filename=Rep1ort.xlsx");

workbook.xlsx.write(res).then(function () {
    res.status(200).end();
});
LKB
  • 457
  • 6
  • 16
  • when you get repsonse on reactjs how to download file – hu7sy Nov 04 '21 at 13:16
  • axios.get(`myRoute`, { responseType: 'arraybuffer' }) .then(response => { const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); FileDownload(blob, `file.xlsx`); // npm " js-file-download" responsible for downloading the file for the user }); on react js I get data as above when file downloaded as corrupt – hu7sy Nov 04 '21 at 13:24
1

I referred this link to wirte the data to excel sheet.

https://www.npmjs.com/package/exceljs

for downloading excel sheet I used this code to download the excel sheet.

 var fileName = "Task" + '_Template.xlsx';
    var tempFilePath = __dirname + "\\public\\template\\" + fileName;
    workbook.xlsx.writeFile(tempFilePath).then(function () {
        res.send(fileName);
    });
Vinoth
  • 972
  • 1
  • 16
  • 47