纯jquery 前端导入 Excel数据 减少服务端压力

纯jquery 前端导入 Excel数据 减少服务端压力

前提是要导入jq库在这里就不再累述

重要的是导入xlsx.core.min.js

我根据xlsx.core.min.js编写自己的工具类

这里是导入数据解析的方法

function parseXlsx( workbook, sheetName, jsonObjects, callback ) {

// 遍历每张表读取

if (workbook.Sheets.hasOwnProperty(sheetName)) {

jsonObjects= XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);

}else

jsonObjects = [];

//处理每条数据

callback(JSON.stringify(jsonObjects), 0 );

}

1

2

3

4

5

6

7

8

9

10

11

将excel的file读取成json的格式(此处只能用于非IE浏览器)

function readXlsxFileFromLocal( file, sheetName, jsonObjects, callback ) {

var reader = new FileReader();

reader.onload = function(e) {

var data = e.target.result;

var workbook = XLSX.read(data, {type: 'binary'});

parseXlsx(workbook, sheetName, jsonObjects, callback);

};

reader.readAsBinaryString(file);

}

1

2

3

4

5

6

7

8

9

将excel的sheet读取成sheet1,sheet2,sheet3的字符串(此处只能用于非IE浏览器)

function readXlsxFilesheetNameSFromLocal( file, callback ) {

var reader = new FileReader();

reader.onload = function(e) {

var data = e.target.result;

var workbook = XLSX.read(data, {type: 'binary'});

if(callback)callback( workbook.SheetNames );

};

reader.readAsBinaryString(file);

}

1

2

3

4

5

6

7

8

9

这里是IE浏览器环境下调取方法同上不再累述

function readXlsxFilesheetNameSFromLocalforIE( file, callback ) {

var binary = "";

var pt = this;

var reader = new FileReader();

reader.onload = function (e) {

var bytes = new Uint8Array(reader.result);

var length = bytes.byteLength;

for (var i = 0; i < length; i++) {

binary += String.fromCharCode(bytes[i]);

}

pt.content = binary;

$(pt).trigger('onload');

var workbook = XLSX.read(binary, {type: 'binary'});

if(callback)callback( workbook.SheetNames );

}

reader.readAsArrayBuffer(file);

}

function readXlsxFileFromLocalforIE( file,sheetName,jsonObjects,callback ) {

var binary = "";

var pt = this;

var reader = new FileReader();

reader.onload = function (e) {

var bytes = new Uint8Array(reader.result);

var length = bytes.byteLength;

for (var i = 0; i < length; i++) {

binary += String.fromCharCode(bytes[i]);

}

pt.content = binary;

$(pt).trigger('onload');

var workbook = XLSX.read(binary, {type: 'binary'});

parseXlsx(workbook, sheetName, jsonObjects, callback);

}

reader.readAsArrayBuffer(file);

}

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

使用时判断是否是IE浏览器

if (!FileReader.prototype.readAsBinaryString) {

console.log("IE");

}else{

console.log("Other");

}

---------------------

作者:chao_yue1992

原文:https://blog.csdn.net/chao_yue1992/article/details/85335558

版权声明:本文为博主原创文章,转载请附上博文链接!

纯jquery 前端导入 Excel数据 减少服务端压力

相关推荐