如何从本地XLSX文件读取数据并将其保存到对象/数组

时间:2019-05-10 12:25:47

标签: javascript arrays parsing xlsx

我需要从本地XLSX文件读取数据并将其保存到对象(或数组)。

数据如下:

我需要这样的数据:

所以我可以使用它(将它与其他对象进行比较/显示...)

这怎么可能?

I tried an AJAX call with the following code:

/* set up XMLHttpRequest */
var url = "Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";

oReq.onload = function(e) {
  var arraybuffer = oReq.response;

  /* convert data to binary string */
  var data = new Uint8Array(arraybuffer);
  var arr = new Array();
  for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
  var bstr = arr.join("");

  /* Call XLSX */
  var workbook = XLSX.read(bstr, {type:"binary"});

  /* DO SOMETHING WITH workbook HERE */
  var first_sheet_name = workbook.SheetNames[0];
  /* Get worksheet */
  var worksheet = workbook.Sheets[first_sheet_name];
  var test = XLSX.utils.sheet_to_json(worksheet,{raw:true})
  console.log(test)
}

oReq.send();

console.log(test) //I can not access it here..

它工作了,我按需获得了对象,但问题是我无法在函数外部访问该对象。 我几个小时前发了一条帖子: How to get an object from an async call (xlsx file) to global scope

2 个答案:

答案 0 :(得分:0)

grouped_check_no is
{'1.4': [{'security': 'IAM'}, {'security': 'EKM'}], '1.3': [{'security': 'SLM'}]}

答案 1 :(得分:0)

不要把它读成二进制字符串,使用

XLSX.read(new Uint8Array(arrayBuffer), {
  type: 'array'
})

您可以使用 async/await 来避免所有回调

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.js"></script>
<script type="module"> // Run as type=module if you want top level await
  const sampleUrl = 'https://file-examples-com.github.io/uploads/2017/02/file_example_XLSX_10.xlsx'
  const res = await fetch(sampleUrl)
  const arrayBuffer = await res.arrayBuffer()
  const uint8 = new Uint8Array(arrayBuffer)

  /* Call XLSX */
  const workbook = XLSX.read(uint8, { type: 'array' })

  /* DO SOMETHING WITH workbook HERE */
  const firstSheetName = workbook.SheetNames[0]
  /* Get worksheet */
  const worksheet = workbook.Sheets[firstSheetName]
  const test = XLSX.utils.sheet_to_json(worksheet, { raw: true })
  console.log(test)
</script>

如果您没有使用顶级 await 那么您必须将代码放在异步函数中

async function loadUrl (url) {
  const res = await fetch(url)
  ...
}