html导出docx文件

本文介绍了一种将HTML内容转换并导出为DOCX文件的方法,利用html-docx-js和file-saver两个npm包,通过简单的Vue组件实现文件导出功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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、点击事件实现导出

<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>

4、没事干,整理了一下写法

<script>
// 引入相关插件
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';

export default {
    data(){
        return{
            // 页面渲染相关
            content:'',
            page:''
        }
    },
  methods: {
    exportDocx() {
      this.content = ` <h1>This is an about page</h1>
      <h2>This is an about page</h2>`;
      this.page = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${this.content}</body></html>`
      const converted = htmlDocx.asBlob(this.page);
      // 用 FielSaver.js里的保存方法 进行输出
      saveAs(converted, 'test.docx');
    }
  },
  render() {
    return (
      <div class="about">
        <button onClick={this.exportDocx}>文件导出</button>
      </div>
    )
  }
}
</script>

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值