将Excel转换为嵌套数组

huangapple go评论80阅读模式
英文:

How to convert excel to nested array

问题

需要帮助将Excel文件转换成嵌套数组,类似于这样:

{
   'a': [{
       'aa': [
           'aaa',
           'aab',
           'aac'
       ],
       'ab': [
           'aba',
           'abc',
           'abd'
       ]
   }],
   'b': [{
       'ba': [
           'baa'
       ],
       'bb': [
           'bba',
           'bbb'
       ]
   }]
}

尝试将大量数据转换成这种格式,谢谢。

英文:

need help converting an Excel file to a nested array

将Excel转换为嵌套数组

to something like this

   {
    'a': [{
        'aa': [
            'aaa',
            'aab',
            'aac'
        ],
        'ab': [
            'aba',
            'abc',
            'abd'
        ]
    }],
    'b': [{
        'ba': [
            'baa'
        ],
        'bb': [
            'bba',
            'bbb'
        ]
    }]
  }

trying to convert a large amount of data to this format, thank you

答案1

得分: 1

你可以将数据导出为CSV并在循环中将其转换为对象:

const csv = `a,aa,aaa
  ,,aab
  ,,aac
  ,ab,aba
  ,,abc
  ,,abd
  b,ba,baa
  ,bb,bba
  ,,bbb`;

const rows = csv.split('\n').map(row => row.split(',').map(col => col.trim()));

const obj = {};
let currentKey = null;

rows.forEach(([k, subKey, value]) => {
    if (k !== "") {
        currentKey = k;
        obj[currentKey] = obj[currentKey] || [];
    }

    if (subKey !== "") {
        const o = { [subKey]: [value] };
        obj[currentKey].push(o);
    } else {
        const lastSubObj = obj[currentKey][obj[currentKey].length - 1];
        const lastSubKey = Object.keys(lastSubObj)[0];
        lastSubObj[lastSubKey].push(value);
    }
});

console.log(obj);
英文:

You can export your data to CSV and transform it to the object in a loop:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const csv = `a,aa,aaa
  ,,aab
  ,,aac
  ,ab,aba
  ,,abc
  ,,abd
  b,ba,baa
  ,bb,bba
  ,,bbb`;

const rows = csv.split(&#39;\n&#39;).map(row =&gt; row.split(&#39;,&#39;).map(col =&gt; col.trim()));

const obj = {};
let currentKey = null;

rows.forEach(([k, subKey, value]) =&gt; {
    if (k !== &quot;&quot;) {
        currentKey = k;
        obj[currentKey] = obj[currentKey] || [];
    }

    if (subKey !== &quot;&quot;) {
        const o = { [subKey]: [value] };
        obj[currentKey].push(o);
    } else {
        const lastSubObj = obj[currentKey][obj[currentKey].length - 1];
        const lastSubKey = Object.keys(lastSubObj)[0];
        lastSubObj[lastSubKey].push(value);
    }
});


console.log(obj);

<!-- end snippet -->

答案2

得分: 1

这是一种改进的形式 @protob answer。只需使用库 xlsx 将Excel转换为2D数组,然后使用一些逻辑将2D数组转换为嵌套的JSON格式。

document.querySelector('input').addEventListener('change', function () {
  var reader = new FileReader();
  reader.onload = function () {
    var arrayBuffer = this.result,
      array = new Uint8Array(arrayBuffer),
      binaryString = String.fromCharCode.apply(null, array);
    var workbook = XLSX.read(binaryString, {
      type: "binary"
    });
    var first_sheet_name = workbook.SheetNames[0];
    var worksheet = workbook.Sheets[first_sheet_name];
    let data = XLSX.utils.sheet_to_json(worksheet, {
      raw: true,
      header: 1
    });
    data = data.map(d => Array.from(d, e => e ?? ''));
    const obj = {};
    let currentKey = null;

    data.forEach(([k, subKey, value]) => {
      if (k !== "") {
        currentKey = k;
        obj[currentKey] = obj[currentKey] || [];
      }

      if (subKey !== "") {
        const o = { [subKey]: [value] };
        obj[currentKey].push(o);
      } else {
        const lastSubObj = obj[currentKey][obj[currentKey].length - 1];
        const lastSubKey = Object.keys(lastSubObj)[0];
        lastSubObj[lastSubKey].push(value);
      }
    });
    console.log(obj);
  }
  reader.readAsArrayBuffer(this.files[0]);
}, false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<input type="file" id="data" accept=".xlsx" />
英文:

This is a form of refinement @protob answer. Just use library xlsx to convert Excel to a 2d array, then use some logic to convert a 2d array into a nested JSON form.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.querySelector(&#39;input&#39;).addEventListener(&#39;change&#39;, function () {
  var reader=new FileReader();
  reader.onload= function () {
    var arrayBuffer=this.result,
      array=new Uint8Array(arrayBuffer),
      binaryString=String.fromCharCode.apply(null, array);
    var workbook=XLSX.read(binaryString, {
      type: &quot;binary&quot;
    });
    var first_sheet_name=workbook.SheetNames[0];
    var worksheet=workbook.Sheets[first_sheet_name];
    let data=XLSX.utils.sheet_to_json(worksheet, {
      raw: true,
      header: 1
    });
    data = data.map(d =&gt; Array.from(d, e =&gt; e??&#39;&#39;));
    const obj={};
    let currentKey=null;

    data.forEach(([k, subKey, value]) =&gt; {
      if (k!==&quot;&quot;) {
        currentKey=k;
        obj[currentKey]=obj[currentKey]||[];
      }

      if (subKey!==&quot;&quot;) {
        const o={ [subKey]: [value] };
        obj[currentKey].push(o);
      } else {
        const lastSubObj=obj[currentKey][obj[currentKey].length-1];
        const lastSubKey=Object.keys(lastSubObj)[0];
        lastSubObj[lastSubKey].push(value);
      }
    });
    console.log(obj);
  }
  reader.readAsArrayBuffer(this.files[0]);
}, false);

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js&quot;&gt;&lt;/script&gt;
&lt;input type=&quot;file&quot; id=&quot;data&quot; accept=&quot;.xlsx&quot; /&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月13日 15:26:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定