vue项目如何使用 SheetJS(xlsx)插件?

简言

SheetJS是一款非常好用的前端处理表格文件的工具。它分社区版和专业版,我们今天来介绍如何简单使用它的社区版。
SheetJS社区版官网

介绍

你应该打开官网浏览具体使用详情。

安装

在这里插入图片描述

打开官网在如上图的Installation板块中可以找到各种运行模块的使用方式。
在这里插入图片描述

一般项目都是webpack或vite这种模块管理打包工具维护的,所以我们看上图的模块。
以npm为例

npm i --save https://cdn.sheetjs.com/xlsx-0.19.2/xlsx-0.19.2.tgz

成功后如下图:
在这里插入图片描述

使用

安装完成后,库可以以xlsx的名称导入:

import {
    
     read, writeFileXLSX } from "xlsx";

如果需要XLS支持,则必须手动导入cpexcel.full.mjs:

/* load the codepage support library for extended support with older formats  */
import {
    
     set_cptable } from "xlsx";
import * as cptable from 'xlsx/dist/cpexcel.full.mjs';
set_cptable(cptable);

导入excel

以vue为例,详细文档如下图,如果你使用了以vue为基础的其他方向的框架,例如(Nuxt)可以参考相应的使用文档。
vuejs使用sheetjs
SheetJs有两种解析excel数据的方法,read(data,options)和readFile(filename,options)。

// 直接解析数据
XLSX.read(data, read_opts)
//	根据文件名解析数据
XLSX.readFile(filename, read_opts)

常用的就是XLSX.read(data, read_opts)方法,它可以直接解析存储在JS字符串、“二进制字符串”、Node.js缓冲区或类型化数组(Uint8Array或ArrayBuffer)中的数据。

  1. 获取数据,将数据转成可被read()方法读取的类型
  2. 读取数据,数据将以对象的形式输出。
  3. 最后可以使用官方已实现的工具函数或者自定义处理函数

下面是示例:

扫描二维码关注公众号,回复: 16284580 查看本文章
<template>
  <div>
    <input
      id="inputFile"
      type="file"
      accept=".xlsx,.xls,.csv"
      @change="change"
    />
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
export default {
      
      
  props: {
      
      
    //  表格数据
    sheetsContent: {
      
      
      type: Object,
      default: () => {
      
      
        return {
      
      }
      }
    }
  },
  emits: ['success', 'update:sheetsContent'],
  data() {
      
      
    return {
      
      
      context: ''
    }
  },
  methods: {
      
      
    change(e) {
      
      
      const file = e.target.files[0]
      const reader = new FileReader()
      reader.readAsBinaryString(file)
      reader.onload = re => {
      
      
        const data = re.target.result
        this.$emit('sucess', data)
        const zzexcel = XLSX.read(data, {
      
      
          type: 'binary'
        })
        console.log(zzexcel)
        this.$emit('update:sheetsContent', zzexcel)
        //	将表中的数据以json格式输出
        //	常见的有 sheet_to_html 、sheet_to_csv等
        const content = XLSX.utils.sheet_to_json(zzexcel.Sheets.Sheet1)
        console.log(content)
        this.context = content
      }
    }
  }
}
</script>

<style></style>

导出excel

导出excel需要有源数据对象,然后才可以导出excel文件。
导出方法有以下三种:

  • XLSX.write(workbook,opts): 从数据生成电子表格字节(文件)。write方法尝试将数据打包到内存中的文件中。默认情况下,会生成XLSX文件,但这可以通过opts参数的bookType属性进行控制。根据type选项,数据可以存储为“二进制字符串”、JS字符串、Uint8Array或缓冲区。
  • XLSX.writeFile(workbook,filename,opts):生成并尝试保存文件。导出文件格式由filename的扩展名决定(SheetJS.xlsx信号XLSX导出、SheetJS.xlsb信号XLSB导出等)。
  • XLSX.writeFileXLSX(workbook,filename,opts): 生成并尝试保存XLSX文件。

示例:

<template>
  <div>
    <table class="table-box">
      <thead>
        <tr>
          <th>表头1</th>
          <th>表头2</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td style="background:#000;color:#fff">2</td>
        </tr>
      </tbody>
    </table>
    <button @click="exportFile">导出</button>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
export default {
      
      
  props: {
      
      
    //  表格数据
    sheetsContent: {
      
      
      type: Object,
      default: () => {
      
      
        return {
      
      }
      }
    }
  },
  emits: ['success', 'update:sheetsContent'],
  data() {
      
      
    return {
      
      
      context: ''
    }
  },
  methods: {
      
      
    exportFile() {
      
      
      const tableDom = document.querySelector('.table-box')
      const workbook = XLSX.utils.table_to_book(tableDom)
      console.log(workbook)
      //  文件名带后缀
      XLSX.writeFileXLSX(workbook, '表1.xlsx')
    }
  }
}
</script>

<style></style>

代码

<template>
  <div>
    <input
      id="inputFile"
      type="file"
      accept=".xlsx,.xls,.csv"
      @change="change"
    />
    <table class="table-box">
      <thead>
        <tr>
          <th>表头1</th>
          <th>表头2</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td style="background:#000;color:#fff">2</td>
        </tr>
      </tbody>
    </table>
    <button @click="exportFile">导出</button>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
export default {
      
      
  props: {
      
      
    //  表格数据
    sheetsContent: {
      
      
      type: Object,
      default: () => {
      
      
        return {
      
      }
      }
    }
  },
  emits: ['success', 'update:sheetsContent'],
  data() {
      
      
    return {
      
      
      context: ''
    }
  },
  methods: {
      
      
    change(e) {
      
      
      const file = e.target.files[0]
      const reader = new FileReader()
      reader.readAsBinaryString(file)
      reader.onload = re => {
      
      
        const data = re.target.result
        this.$emit('sucess', data)
        const zzexcel = XLSX.read(data, {
      
      
          type: 'binary'
        })
        console.log(zzexcel)
        this.$emit('update:sheetsContent', zzexcel)
        const content = XLSX.utils.sheet_to_json(zzexcel.Sheets.Sheet1)
        console.log(content)
        this.context = content
      }
    },
    exportFile() {
      
      
      const tableDom = document.querySelector('.table-box')
      const workbook = XLSX.utils.table_to_book(tableDom)
      console.log(workbook)
      //  文件名带后缀
      XLSX.writeFileXLSX(workbook, '表1.xlsx')
    }
  }
}
</script>

<style></style>

结语

结束了

猜你喜欢

转载自blog.csdn.net/qq_43231248/article/details/129039257