Vue中html导出docx文件和table导出excel

12 篇文章 1 订阅
7 篇文章 3 订阅

html导出docx文件 

方法一、技术实现:fileSaver.js+html-docx-js

html-docx.js,这个比较是16年的插件,不适合现在的,主要就是with(obj){}这个已经不符合规范,有的框架不适用

1.npm安装

$ npm install --save html-docx-js
$ npm install --save file-saver

2.引入

import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';

3.导出word

<template>
  <div class="about">
    <button @click="this.exportClick">an</button>
  </div>
</template>

<script>
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
export default {
  methods: {
    exportClick() {
      var content = ` <h1>This is an about page</h1>
      <h2>This is an about page</h2>`
      var page = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' + content + '</body></html>'
      var converted = htmlDocx.asBlob(page);
      // 用 FielSaver.js里的保存方法 进行输出
      saveAs(converted, 'test.docx');
    }
  }
}
</script>

方法二:jQuery中的插件jquery.wordexport.js+fileSaver.js

说明:在Vue中使用

 1.在index.html全局引入jQuery

 2.cmd安装FileSaver.js  , 在需要的组件中引入file-saver

npm install file-saver --save

 3.在需要的组件中引入

4.使用

 

 

<div class="word">
        <h1>我们的梦想来自内心深处的孤独</h1>>
        <p align="center" style="font-size:20pt;font-weight:bold;">JS导出Word文档</p>
        <div>我们来自同一个世界</div>
    </div>
    <input type="button" value="导出word">
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
    <script type="text/javascript" src="FileSaver.js"></script>
    <script type="text/javascript" src="jquery.wordexport.js"></script>
    <script>
        $(function () {
            $("input[type='button']").click(function (event) {
                $(".word").wordExport('word文档');
            });
        })
    </script>

可以使用xdoc http://www.xdocin.com/web.html

table导出excel

1. 安装依赖

npm install --save xlsx
npm install --save file-saver

2. 表格添加属性

标签添加ref属性,用于获取该元素el;也可添加id属性获取

<table ref="exportTableRef"> ... </table>
或
<table  id="table" > ... </table>

3. js代码

// 导入依赖
import XLSX from 'xlsx'
import FileSaver from 'file-saver'

// 导出方法
exportBtn() {
  // 获取表格元素
  const el = this.$refs.exportTableRef1.$el
  // 文件名
  const filename = '导出.xlsx'
  /* generate workbook object from table */
  const wb = XLSX.utils.table_to_book(el)
  /* 或者用id */
  // const wb = XLSX.utils.table_to_book(document.getElementById("id"))
  /* get binary string as output */
  const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
  try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)
  } catch (e) {
    console.log(e)
  }
  return wbout
}

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值