首页 > 解决方案 > 是否可以读取 Excel 表并纯粹在前端显示其内容?

问题描述

我在想我是否可以使用 XLSX 读取 Excel 表的内容并在前端显示其内容。

我尝试使用读取文件

tmpArray= [];
reader.onload = function(e : any) {
   var data = new Uint8Array(e.target.result);
   var workbook = XLSX.read(data, {type: 'array'});

   let worksheet = workbook.Sheets[workbook.SheetNames[0]];

   // sample values //
   let desired_cell = worksheet['B5'];
   let cellB16 = worksheet['B16'];
   // sample values //
   let desired_value12 = (cellB16 ? cellB16.v : undefined);
   tmpArray.push[desired_value12];
};


but outside this onload function, array of tmpArray don't exist anymore.
So what i wanted is to access the tmpArray and it's contents after the onload function. Is there any work around to do this?

标签: excelangulartypescript

解决方案


请进行以下更改,您将能够tmpArray从任何地方访问 的值。

tmpArray; // changed here and moved it to outside the function

let self = this; // please note this change
reader.onload = function(e : any) {
   var data = new Uint8Array(e.target.result);
   var workbook = XLSX.read(data, {type: 'array'});

   let worksheet = workbook.Sheets[workbook.SheetNames[0]];

   // sample values //
   let desired_cell = worksheet['B5'];
   let cellB16 = worksheet['B16'];
   // sample values //
   let desired_value12 = (cellB16 ? cellB16.v : undefined);
   self.tmpArray = desired_value12; // changed here
};

推荐阅读