要修改Excel数据并导出,您需要使用以下步骤:

  1. 将Excel文件导入Vue组件中。您可以使用第三方库如xlsxfile-saver来实现这一点。例如,使用xlsx库:
import * as XLSX from 'xlsx';

export default {
  data() {
    return {
      workbook: null,
      sheetName: null
    }
  },
  methods: {
    handleFileUpload(e) {
      const file = e.target.files[0];
      const reader = new FileReader();
      reader.onload = (evt) => {
        const data = evt.target.result;
        this.workbook = XLSX.read(data, {type: 'binary'});
        this.sheetName = this.workbook.SheetNames[0];
      };
      reader.readAsBinaryString(file);
    }
  }
}
  1. 将Excel表格渲染到页面上。您可以使用vue-xlsx-table或手动渲染表格。例如,手动渲染:
<template>
  <table>
    <thead>
      <tr>
        <th v-for="col in columns" :key="col">{{ col }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, index) in rows" :key="index">
        <td v-for="(cell, j) in row" :key="'cell' + j">{{ cell }}</td>
      </tr>
    </tbody>
  </table>
</template>

<script>
export default {
  props: ['sheetData'],
  computed: {
    columns() {
      if (!this.sheetData) return [];
      const firstRow = Object.keys(this.sheetData[0]);
      return firstRow;
    },
    rows() {
      if (!this.sheetData) return [];
      return this.sheetData.map(row => Object.values(row));
    }
  }
}
</script>
  1. 使表格可编辑。您可以使用vue2-handsontable或手动实现编辑。例如,手动实现:
<template>
  <table>
    <thead>
      <tr>
        <th v-for="col in columns" :key="col">{{ col }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, index) in rows" :key="index">
        <td v-for="(cell, j) in row" :key="'cell' + j" @input="updateCell(index, j, $event.target.value)" :contenteditable="true">{{ cell }}</td>
      </tr>
    </tbody>
  </table>
</template>

<script>
export default {
  props: ['sheetData'],
  methods: {
    updateCell(rowIndex, colIndex, value) {
      this.sheetData[rowIndex][Object.keys(this.sheetData[rowIndex])[colIndex]] = value;
    }
  }
}
</script>
  1. 导出修改后的数据。您可以使用以下代码将修改后的数据导出为Excel文件:
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

export default {
  props: ['workbook', 'sheetName', 'sheetData'],
  methods: {
    exportExcel() {
      const sheet = XLSX.utils.json_to_sheet(this.sheetData);
      this.workbook.Sheets[this.sheetName] = sheet;
      const wbout = XLSX.write(this.workbook, { bookType: 'xlsx', type: 'binary' });
      saveAs(new Blob([this.s2ab(wbout)], { type: 'application/octet-stream' }), 'modified_data.xlsx');
    },
    s2ab(s) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
      return buf;
    }
  }
}

将该方法绑定到“导出”按钮或其他事件,并传递当前的工作簿、表格名称和修改后的数据

vue修改excel数据后再导出

原文地址: https://www.cveoy.top/t/topic/hbVO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录