Vue3导出Word表格

文章目录

依赖版本

最终效果

模板文件

表格数据结构

代码实现

Word语法总结


依赖版本

  • "vue": "^3.4.15"

  • "jszip-utils": "^0.1.0"

  • "pizzip": "^3.1.6"

  • "docxtemplater": "^3.46.2"

  • "file-saver": "^2.0.5"

最终效果

模板文件

注:word文件在顶部

表格数据结构

tableInformations: [
    {
        val: string,
        children:[
            {
                courseName: string,
                credits: number,
                data0: string,
                data1: string,
                data2: string,
                data3: string,
                data4: string,
                data5: string,
                data6: string,
                data7: string,
                data8: string,
                data9: string,
                data10: string,
                isCoreCourse: number,
                isCourse: boolean,
                isTotal: boolean,
                practiceHours: string,
                teachingHours: string,
                totalHours: string,
                totalSemester: Array<string>[11]
            },
            ...
        ],
        isOneLine?: boolean,
        totalCredits?: number 
    },
    ...
]

代码实现

const outPutWord = async () => {
  JSZipUtils.getBinaryContent(`${'/demo'}.docx`, (error, content) => {
    // 抛出异常
    if (error) {
      throw error
    }
    // 创建一个PizZip实例,内容为模板的内容
    const zip = new JSZip(content)
    // 创建并加载docxtemplater实例对象
    const doc = new Docxtemplater().loadZip(zip)
    // 设置模板变量的值
    doc.setData({
      tableInformations: tableInformations
    })
    try {
      // 用模板变量的值替换所有模板变量
      doc.render()
    } catch (error) {
      // 抛出异常
      const e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties
      }
      console.log(JSON.stringify({ error: e }))
      throw error
    }
    // 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
    const out = doc.getZip().generate({
      type: 'blob',
      mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    })
    // 将目标文件对象保存为目标类型的文件,并命名,可自定义名称
    saveAs(out, '模板文件.docx')
  })
}

Word语法总结

  • 循环:{#forName}{/forName}
  • 判断:{#ifName}{/ifName}
  • 判断反面:{^ifName}{/ifName}
  • 数据渲染:{dataName}

注:上述的forName、ifName和dataName应该写作对应的变量名称

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值