将 xlsx 转换为 JSON 并以特定格式存储

Converting xlsx to JSON and storing in a specific format

提问人:Muhammad Tajwar 提问时间:11/18/2023 更新时间:11/18/2023 访问量:22

问:

我正在做一个项目,我被困在某一点:

所以我有xlsx表和一些数据:在这里输入图像描述

当我像这样转换为 JSON 时:

if (selectedFile) {
const formData = new FormData();
formData.append("file", selectedFile);
const workbook = XLSX.read(await selectedFile.arrayBuffer(), {
type: "array",
      });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
}

和控制台.log(jsonData):

结果是它分别取每一行并制作每一行的对象:

在此处输入图像描述

但我希望这个jsonData以不同的方式存储

 `if (selectedFile) {
const formData = new FormData();
formData.append("file", selectedFile);
const workbook = XLSX.read(await selectedFile.arrayBuffer(), {
type: "array",
      });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

if (jsonData.length > 0) {
const headers = data[0];

Create a dictionary to store column names and their values as arrays
const columnDict: { [key: string]: string[] } = {};

headers.forEach((header: string) => {
columnDict[header] = data
            .slice(1)
            .map((row: any) => row[headers.indexOf(header)]);
        });

Update state with the column data
setColumnData(columnDict);
      }
}`

I have tried like this but now :

I am expecting it like :

> ```
> Chemicals: ["Silicon","2nd value", "3rd value",....]
> Diameter: [1,"2nd value", "3rd value",....]
> Effect endpoint: ["Feret Minimal","2nd value", "3rd value",....]
> Effect endpoint type: ["Median","2nd value", "3rd value",....]
> Endpoint: ["Nano","2nd value", "3rd value",....]
> Endpoint Method: ["Invest1","2nd value", "3rd value",....]
> Endpoint category: ["Solid","2nd value", "3rd value",....]
> Material: ["Light","2nd value", "3rd value",....]
> Medium: ["CORE","2nd value", "3rd value",....]
> Name: ["1.1_SiC@TiO2_60","2nd value", "3rd value",....]
> Percentage: ["0.22","2nd value", "3rd value",....]
> Project: ["Sunshine","2nd value", "3rd value",....]
> ```

all the values would be in a array according to the corresponding headers.

Thank you so much in advance
JavaScript 反应JS JSON 打字稿 xlsx

评论

0赞 Slai 11/25/2023
您可以考虑将对象数组转换为数组对象 stackoverflow.com/questions/37988451/...

答: 暂无答案