如何在 JSON 输出中将空单元格保持为空而不是忽略单元格 (Vue-XLSX)

我正在阅读一个 excel 文件并在 Nuxt 项目中使用 vue-xlsx 将其转换为 JSON 对象。但是可以有空单元格。 Vue-xlsx 忽略它们。

如何在 JSON 输出中将空单元格保持为空而不是忽略单元格 (Vue-XLSX)

返回的JSON对象是这样的:

[ 
  { "Header1": "a","Header3": "c" },{ "Header1": "d","Header2": "e","Header3": "f" },{ "Header1": "g","Header2": "h","Header3": "i" } 
]

我不需要使用 'xlsx-table' 组件打印它,因为我需要 JSON 对象。 试图以这种方式将 defval 属性作为选项传递。但没有成功。

<section>
  <input type="file" @change="onChange" />
  <xlsx-read :options="options" :file="file">
    <xlsx-json :sheet="selectedSheet" >
      <template #default="{collection}">
        <!-- <xlsx-table :sheet="selectedSheet" /> -->
        <div>
          {{ json = collection }}
        </div>
      </template>
    </xlsx-json>
  </xlsx-read>
</section>

<script>
export default {
  data() {
    return {
      file: null,options: {
        defval: "",},json: null,selectedSheet: 0,};
  },}
</script>

我需要一些帮助来生成这种 JSON 对象:

如何在 JSON 输出中将空单元格保持为空而不是忽略单元格 (Vue-XLSX)

我如何使用 Vue-XLSX 做到这一点。

hxj752367319 回答:如何在 JSON 输出中将空单元格保持为空而不是忽略单元格 (Vue-XLSX)

这可以通过 VanillaJS 完成,无需依赖 ?

如果我们从

开始
vue-xlxs

我们可以有以下内容

[ 
  { "Header1": "a","Header3": "c" },{ "Header1": "d","Header2": "e","Header3": "f" },{ "Header1": "g","Header2": "h","Header3": "i" } 
]

它会在最后创建这个

<script>
export default {
  data() {
    return {
      array: [
        { Header1: 'a',Header3: 'c' },{ Header1: 'd',Header2: 'e',Header3: 'f' },{ Header1: 'g',Header2: 'h',Header3: 'i' },],}
  },mounted() {
    const neededHeaders = ['Header1','Header2','Header3']
    const arrayWithFallback = this.array.map((row) => {
      for (const headerKey of neededHeaders) {
        if (!(headerKey in row)) {
          // if you're missing one of the header,let's create a default value for it
          row[headerKey] = 'your-fallback-here' // can also be an empty string of course
        }
      }
      return row
    })
    console.log('arrayWithFallback',arrayWithFallback)
  },}
</script>
,

我使用了 documentation 中提到的“xlsx-json”组件中提到的“解析”事件。这是我的完整 Nuxt 组件:

如果您有“标题信息”:

<template>
  <div>
    <h3>Import XLSX</h3>
    <input type="file" @change="onChange" />
    <xlsx-read :file="file">
      <xlsx-json @parsed = "parsFunc">
        <template #default="{collection}">
          <div class="divShow">
            {{ collection }}
          </div>
        </template>
      </xlsx-json>
    </xlsx-read>
  </div>
</template>

<script>
/* put the address that matches for your app */
import { XlsxRead,XlsxJson } from "~/node_modules/vue-xlsx/dist/vue-xlsx.es.js";

export default {
  components: {
    XlsxRead,XlsxJson
  },data() {
    return {
      file: null,/* this array contains the exact words that you write on the first line of xlsx file */
      headerData: ["Header1","Header2","Header3"],};
  },computed: {
      lengData: function() {
          return this.headerData.length;
      } 
  },methods: {
    onChange(event) {
      this.file = event.target.files ? event.target.files[0] : null;
    },sortOutput(elemEach) {
        /* this function sorts the new object */
        let arrObj = Object.entries(elemEach);
        arrObj.sort((a,b) => a[0].localeCompare(b[0]));
        let arraySorted = Object.fromEntries(arrObj);
        return arraySorted; 
    },parsFunc(event) {
        /* this function loops throught elements in "xlsx" file and replaces empty cells with "" */
        let counter = 0;
        event.forEach(element => {
            for (let it = 0; it < this.lengData; it++) {
                
                if( element[this.headerData[it]] == undefined ) {
                    element[this.headerData[it]] = "";
                }
                
            }

            let sortedElem = this.sortOutput(element);
            
            event[counter] = sortedElem;
            
            counter++;
        }); // end of forEach
    
    }
  }
};
</script>

<style scoped>
/* this is the styles that I used */
.divShow {
    background-color: #865611;
    padding: 50px;
    color: white;
}
</style>

如果要动态生成“header info”:

<template>
  <div>
    <h3>Import XLSX</h3>
    <input type="file" @change="onChange" />
    <xlsx-read :file="file">
      <xlsx-json @parsed = "parsFunc">
        <template #default="{collection}">
          <div class="divShow">
            {{ collection }}
          </div>
        </template>
      </xlsx-json>
    </xlsx-read>
  </div>
</template>

<script>
/* put the address that matches for your app */
import { XlsxRead,headerData: [],findHeader(elem,newArr) {
      /* this function finds the headers of the "xlsx" file */
      this.headerData = [];
      let convertArr = Object.entries(elem);
      convertArr.forEach(element2 => {
      newArr.push( Object.entries(element2[1]).length );
      });

      let indexOfMaxValue = newArr.reduce((iMax,x,i,arr) => x > arr[iMax] ? i : iMax,0);
      
      let arrayExtract =  Object.entries( convertArr[indexOfMaxValue][1] );

      arrayExtract.forEach(element3 => {
        this.headerData.push(element3[0]);
      });

      this.replaceEmpty(elem);

    },parsFunc(event) {
        /* this function acts after submitting file and call another function to find "headers" */
        let emptyArr = [];
        this.findHeader(event,emptyArr);
    },replaceEmpty: function(eventPass) {
      /* this function loops throught elements in "xlsx" file and replaces empty cells with "" */
      let counter = 0;
      eventPass.forEach(element => {
          
            for (let it = 0; it < this.lengData; it++) {
                
              if( element[this.headerData[it]] == undefined ) {
                      element[this.headerData[it]] = "";
              }
                
            }

            let sortedElem = this.sortOutput(element);
            
            eventPass[counter] = sortedElem;
            
            counter++;
        }); // end of forEach

    } // end of replaceEmpty

  }
};
</script>

<style scoped>
/* this is the styles that I used */
.divShow {
    background-color: #865611;
    padding: 50px;
    color: white;
}
</style>

但要使用此版本,您的xlsx 文件中必须至少有 整行。例如,此代码不适用于这种 xlsx 文件:

enter image description here

本文链接:https://www.f2er.com/23026.html

大家都在问