HTLF

一步一个脚印,走出高度...

导航

vue 基于exceljs导出Excle

安装依赖

  1. exceljs插件
  2. file-saver下载插件
npm i exceljs
npm i file-saver

引用

import * as ExcelJS from 'exceljs'
import FileSaver from 'file-saver'

使用

// 设置标题列
const exportTableProp = ref([
  {
    header: '编号', //表头列名
    key: 'number', //每列的数据源
    width: 14, //列宽
  },
  {
    header: '姓名',
    key: 'name',
    width: 24,
  },
  {
    header: '年级',
    key: 'class',
    width: 14,
  },
  {
    header: '学校',
    key: 'school',
    width: 14,
    style: { // 添加样式
      alignment: {
        horizontal: 'center',
        vertical: 'center',
      },
    },
  },
])

// 表格数据
const tableData = ref([
  {
    number: '1',
    name: '张三',
    class: '大一',
    school: '清华大学',
  },
  {
    number: '1',
    name: '张三',
    class: '大一',
    school: '清华大学',
  },
])

// 下载excel
const dowExcel = () => {
  // 新建一个 excel 工作簿
  const workbook = new ExcelJS.Workbook()

  // 创建一个新的工作表
  const worksheet = workbook.addWorksheet('Sheet1')

  // 添加表头
  worksheet.columns = exportTableProp.value

  // 自定义表头字段
  worksheet.columns = exportTableProp.value.map((item) => {
    return {
      header: item.header, // 表头对应的字段
      key: item.key, // 内容对应的字段
      width: item.width, // 宽度对应的字段
    }
  })

  // 添加数据
  worksheet.addRows(tableData.value)

  // 下载工作文件
  workbook.xlsx.writeBuffer().then((buffer) => {

    // 使用file-saver 下载
    saveAs(new Blob([buffer], { type: 'application/octet-stream' }), '清华、央美学生名单.xlsx')
    
    // 或
    var fileExcle = new Blob([buffer], { type: 'application/octet-stream' })
    saveAs(fileExcle, '清华、央美学生名单.xlsx')

    // a标签下载Excel
    const link = document.createElement('a')
    const url = URL.createObjectURL(new Blob([buffer], { type: 'application/octet-stream' }))
    link.href = url
    link.download = '清华、央美学生名单.xlsx'
    link.click()
    URL.revokeObjectURL(url)
    a.remove()
  })
}

// 调用
onMounted(() => {
  dowExcel()
})

样式参考
样式参考

posted on 2025-01-16 15:25  HTLF  阅读(18)  评论(0)    收藏  举报