我不知道如何用SheetJS转换后定义我的数组

时间:2019-11-13 07:37:20

标签: javascript json excel templates literals

我是JS的新手,因此我对此表示歉意。

我为工具编写了一些代码,该工具使用模板文字来显示对象数组中的新闻卡:

document.getElementById("Newscards").innerHTML =`
 <p class="Newscardstitle">External News</p>

 ${Worksheet.reverse()
 	.map(function(Atribute){
 	return `
 	<div class="newcard">
 	<div class="containernewphoto">
 	<img class= "newphoto" src="${Atribute.Image}"></img> </div>
 	<div class="containernewtext"> <p class="newdate"> ${Atribute.Date}</p>
 	<p class="newheadline"><a href="${Atribute.Link}">${Atribute.Headline}</a></p>
 	
 	<p class= "newdescription">${Atribute.Description}</p>
</div>
 	</div>
 	`
 }).join('')}

 `
现在我正在使用来自json的js文件,如下所示:

const Articles =
[
  {
    "Date": "2019-11-04",
    "Headline": "",
    "Description": "",
    "Link": "",
    "Icon": "Military",
    "Latitude": 36.174523,
    "Longitude": 36.637775,
    "Image": ".jpg",
    "Added": "06/11/2019"
  },
...
]

但是,这非常不方便,因为我必须更改XLSX,然后在在线平台上将其转换为json并手动更改json js文件。我以为SheetJS可以帮助我将XLSX自动转换为JSON,所以我添加了以下代码:

  /* set up XMLHttpRequest */
  var url = "SyriaNews.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];
            console.log(XLSX.utils.sheet_to_json(worksheet, {
                raw: true
            }));
        }

        oReq.send();

 document.getElementById("Newscards").innerHTML =`
 <p class="Newscardstitle">External News</p>

 ${**Worksheet**.reverse()
 	.map(function(Atribute){
 	return `
 	<div class="newcard">
 	<div class="containernewphoto">
 	<img class= "newphoto" src="${Atribute.Image}"></img> </div>
 	<div class="containernewtext"> <p class="newdate"> ${Atribute.Date}</p>
 	<p class="newheadline"><a href="${Atribute.Link}">${Atribute.Headline}</a></p>
 	
 	<p class= "newdescription">${Atribute.Description}</p>
</div>
 	</div>
 	`
 }).join('')}

 `          

在控制台中,我获得了正确的对象数组,但是在XLSX转换后无法定义JSON对象,因此可以为模板文字调用它。我不知道必须更改哪一部分。

0 个答案:

没有答案