How to export excel using nodejs

Source: Internet
Author: User

How to export excel using nodejs

This document describes how to export an excel file from nodejs. Share it with you for your reference. The details are as follows:

Nodejs generates and downloads excel files for query data. The excel-export plug-in code is as follows:

Excel. js code:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

Var extend = require ("extend ");

Var fs = require ("fs ");

Var excelExport = require ('excel-export ');

Var guid = require ('guid ');

Var path = require ('path ');

Var excel = function (){

This. req = null;

This. resp = null;

};

/**

* Generate an excel file

* @ Param params

*/

Excel. prototype. createExcel = function (params ){

Var setting = {savePath: "uploadFile/excel /"};

Setting = extend ({}, setting, params );

Var uuid = guid. create ();

Var data = params. data | "";

Var result = excelExport.exe cute (data );

Var name='excel'{uid='.xlsx ';

Var filePath = path. resolve (setting. savePath, name );

Fs. writeFile (filePath, result, 'binary ', function (err ){

Setting. cb (filePath );

});

}

/**

* Calculate the last breakpoint information.

* @ Param range

* @ Returns {number}

* @ Private

*/

Excel. prototype. _ calStartPosition = function (range ){

Var startPos = 0;

If (typeof range! = 'Undefined '){

Var startPosMatch =/^ bytes = ([0-9] +)-$/. exec (range );

StartPos = Number (startPosMatch [1]);

}

Return startPos;

}

Excel. prototype. _ configHeader = function (config ){

Var startPos = config. startPos,

FileSize = config. fileSize,

Resp = this. resp;

// If startPos is 0, the object is downloaded from 0; otherwise, the object is downloaded from a breakpoint.

If (startPos = 0 ){

Resp. setHeader ('Accept-range', 'bytes ');

} Else {

Resp. setHeader ('content-range', 'bytes '+ startPos +'-'+ (fileSize-1) +'/'+ fileSize );

}

Resp. writeHead (206, 'partial content ',{

'Content-type': 'application/octet-stream'

});

}

Excel. prototype. _ init = function (filePath, down ){

Var config = {};

Var self = this;

Fs. stat (filePath, function (error, state ){

If (error)

Throw error;

Config. fileSize = state. size;

Var range = self. req. headers. range;

Config. startPos = self. _ calStartPosition (range );

Self. config = config;

Self. _ configHeader (config );

Down ();

});

}

/**

* Download an object

* @ Param filePath: file path

* @ Param req

* @ Param res

* @ Param isDeleted: whether to delete the file after the download is complete. true: delete the file.

*/

Excel. prototype. download = function (filePath, req, res, isDeleted ){

Var self = this;

Self. req = req;

Self. resp = res;

Path. exists (filePath, function (exist ){

If (exist ){

Self. _ init (filePath, function (){

Var config = self. config

Resp = self. resp;

FReadStream = fs. createReadStream (filePath ,{

Encoding: 'binary ',

BufferSize: 1024*1024,

Start: config. startPos,

End: config. fileSize

});

FReadStream. on ('data', function (chunk ){

Resp. write (chunk, 'binary ');

});

FReadStream. on ('end', function (){

// Whether to delete the object

If (isDeleted ){

Fs. unlink (filePath, function (err, res ){

});

}

Resp. end ();

});

});

}

Else {

Console. log ('the file does not exist! ');

Return;

}

});

}

Module. exports = new excel ();

Call method:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

Var excel = require ('../lib/excelHelper. js ');

Exports. exportExcel = function (req, res ){

Var conf = {};

Conf. cols = [

{Caption: 'string', type: 'string '},

{Caption: 'date', type: 'string '},

{Caption: 'bool ', type: 'bool '},

{Caption: 'number', type: 'number '}

];

Conf. rows = [

['Pi ', '2017-06-29', true, 2015],

["E", '2017-06-29 ', false, 2015]

];

Var filename = "Export excel.xlsx ";

Res. setHeader ('content-disposition', 'attachment; filename = '+ encodeURIComponent (filename ));

Excel. createExcel ({

Data: conf,

SavePath: "uploadFile/excel /",

Cb: function (path ){

Excel. download (path, req, res, true );

}

});

}

I hope this article will help you design nodejs programs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.