当前位置: 代码网 > it编程>编程语言>Javascript > 前端导出word文件的多种方式以及导出excel文件

前端导出word文件的多种方式以及导出excel文件

2024年09月08日 Javascript 我要评论
先看效果:这是页面中的table这是导出后的效果:使用模板导出需要的依赖:npm 自行安装,需要看官网的具体参数自行去github上面找对应的参数 "docxtemplater": "^3.46.0"

先看效果:

这是页面中的table

这是导出后的效果:

使用模板导出

需要的依赖:

npm 自行安装,需要看官网的具体参数自行去github上面找对应的参数

 	"docxtemplater": "^3.46.0",
    "pizzip": "^3.1.6",
    "jszip-utils": "^0.1.0",
    "file-saver": "^2.0.5",

具体代码:(先看word模板,在看代码,word中的变量和代码中 doc.setdata() 是一一对应的)

<template>
  <div class="button-box">
    <a-space>
      <a-button type="danger" @click="downword2">模板导出word文件</a-button>
    </a-space>
  </div>
</template>

<script lang="ts">
import { definecomponent, onmounted, reactive, proptype, ref } from 'vue';
import { message } from 'ant-design-vue';
import moment from 'moment';
import { downloadpdf } from '../../../../utils/utils';
import { usetable } from './hooks/usetable';
import xlsx from 'node-xlsx';

import docxtemplater from 'docxtemplater';
import pizzip from 'pizzip';
import jsziputils from 'jszip-utils';
import { saveas } from 'file-saver';

export default definecomponent({
  props: {
    /**
     * 基础数据
     */
    basedata: {
      type: object as proptype<{
        taskid: string;
        barcodeid: string;
      }>,
      default: {},
    },
    /**
     * 样本名称
     */
    barcodename: {
      type: string,
    },
  },

  setup(props) {
    let width = 100;
    const { barcodename } = props;
    const { taskid, barcodeid } = props.basedata;
    const { tableconfig, tableconfigleft, getdta } = usetable();



    onmounted(() => {
      barcodename ? getdta(taskid, barcodename) : '';
    });
    
    const tablevalue = reactive({
      unit: '中国',
      date: undefined,
      sampletype: '你猜',
      people: '黄种人',
      name: '夜空',
      sex: '男',
      age: '25',
      work: '开发',
      id: '',
      jiance: '商品化试剂盒',
      date2: undefined,
    });

   
    const downword2 = () => {
      let docxname = '导出word.docx';
      jsziputils.getbinarycontent('/test.docx', function (error: any, content: any) {
        // test.docx是模板(这里我放到public公共文件夹下面了)。我们在导出的时候,会根据此模板来导出对应的数据
        // 抛出异常
        if (error) {
          throw error;
        }

        // 创建一个pizzip实例,内容为模板的内容
        let zip = new pizzip(content);
        // 创建并加载docx templater实例对象
        let doc = new docxtemplater().loadzip(zip);
        // 设置模板变量的值  主要变量替换在这里
        doc.setdata({
          name: tablevalue.name,
          unit: tablevalue.unit,
          date: moment(tablevalue.date).format('yyyy-mm-dd'),
          sampletype: tablevalue.sampletype,
          sex: tablevalue.sex,
          age: tablevalue.age,
        });

        try {
          // 用模板变量的值替换所有模板变量
          doc.render();
        } catch (error: any) {
          // 抛出异常
          let e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          };
          console.log(
            json.stringify({
              error: e,
            }),
          );
          throw error;
        }

        // 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
        let out = doc.getzip().generate({
          type: 'blob',
          mimetype: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        });
        // 将目标文件对象保存为目标类型的文件,并命名
        saveas(out, docxname);
      });
    };

    return {
      downword2,
      getdta,
      tableconfig,
      tableconfigleft,
      tablevalue,
      downloadpdf,
      value4: ref('less'),
    };
  },
});
</script>

<style lang="less" scoped>

</style>

前端通过模板字符串导出word文件

包依赖:

 "file-saver": "^2.0.5",

代码

import filesaver from 'file-saver';
import htmldocx from "html-docx-js/dist/html-docx"
import { g } from '@/global';
const { rooturl, rbactoken } = g;
let cycle_info1 = [
  {
    name: '事件类型',
    key: 'eventtypename',
  },
  {
    name: '地点定位',
    key: 'locationaddress',
  },
  {
    name: '上报时间',
    key: 'reporttime',
  },
  {
    name: '人员姓名',
    key: 'reportusername',
  },
  {
    name: '联系方式',
    key: 'reportuserphone',
  },
]

const model = (reportinfodetail: any, list: any, eventstate: any) => {
  // console.log(reportinfodetail, list, eventstate);

  return (
    `
    <!doctype html>
      <html>

<head>
  <style>
    .maxbox {
      padding: 0px 15px;
      overflow-y: auto;
      height: 50vh;
    }

    .frombox {}

    .formtitle_first {
      color: #1c69f7;
      font-size: 23px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .formtitle_second {
      font-weight: bold;
      font-size: 16px;
      margin-bottom: 10px;
    }

    .formcontent_box {
      margin-bottom: 5px;
    }

    .formcontent_box_title {
      min-width: 60px;
    }

    .display_flex {
      display: flex;
    }
  </style>
</head>

<body>
  <div class="maxbox">
    <div class="frombox">
      <div class="formtitle_first">上报信息</div>
      <div class="formtitle_second">上报信息</div>
      <div class="formcontent_box display_flex" style="display:flex">
        <span class="formcontent_box_title" >事件类型:</span>
        <span>${reportinfodetail['eventtypename']}</span>
      </div>
      <div class="formcontent_box display_flex" style="display:flex">
        <span class="formcontent_box_title">地点定位:</span>
        <span>${reportinfodetail['locationaddress']}</span>
      </div>
      <div class="formcontent_box display_flex" style="display:flex">
        <span class="formcontent_box_title">上报时间:</span>
        <span>${reportinfodetail['reporttime']}</span>
      </div>
      <div class="formcontent_box display_flex" style="display:flex">
        <span class="formcontent_box_title">人员姓名:</span>
        <span>${reportinfodetail['reportusername']}</span>
      </div>
      <div class="formcontent_box display_flex" style="display:flex">
        <span class="formcontent_box_title">联系方式:</span>
        <span>${reportinfodetail['reportuserphone']}</span>
      </div>
    
      <div class="formtitle_second">图片附件</div>
      <div class="formcontent_box">
        ${reportinfodetail['picids']?.map((res1: any, idx1: any) => {
      return `
        <img width='240' height='160' src="${rooturl}/fyvolunteer/file/download/${res1}?rbactoken=${rbactoken}"
          style='margin-right:5px'
        />
        ${((idx1 + 1) % 2 == 0) ? `<br />` : ''}
        `
    })
    }
      </div>
      <div class="formtitle_second">事件描述</div>
      <div class="formcontent_box">${reportinfodetail['description']}</div>
    </div>
    ${reportinfodetail.assigninfo.length != 0 ?
      `
      <div class="frombox">
      <div class="formtitle_first">指派信息</div>
      <div class="formtitle_second  display_flex">指派信息</div>
      <div class="formcontent_box">
        <div class="formcontent_box_title">指派单位:
          ${reportinfodetail.assigninfo.map((res: any, idx: any) => {
        return `
              <span style="margin-right:15px">
                ${res.departmentname}
              </span>
              `
      })
      }
        </div >
      </div >
      <div class="formcontent_box  display_flex">
          <span class="formcontent_box_title">指派时间:</span>
          <span>${!!reportinfodetail?.assigninfo[0]?.assigntime ? reportinfodetail?.assigninfo[0]?.assigntime : ""}</span>
      </div>
    </div>
      `: ''

    }  

    <div class="frombox">
      <div class="formtitle_first">处置信息</div>
      ${reportinfodetail.handleinfo.length != 0 ?
      reportinfodetail.handleinfo.map((itm: any, idx: any) => {
        return `
        <div class="formtitle_second">单位${idx + 1}:${itm['claimdepartmentname']}</div>
        <div class="formtitle_second">签收信息</div>
        <div class="formcontent_box display_flex"
        style="width:32vw;justify-content: space-between;">
          <div>
            <span>签收单位:${itm['claimdepartmentname']}</span>
          </div>
          <div>
            <span>签收时间:${itm['claimtime']}</span>
          </div>
        </div >
        <div class="formtitle_second">图片附件</div>
        <div class="formcontent_box">
          ${itm['handletime'] != null ?
            itm['handlepicids']?.map((res1: any, idx1: any) => {
              return `
          <img width="240" height="160"
            src="${rooturl}/fyvolunteer/file/download/${res1}?rbactoken=${rbactoken}"
            style="margin-right:5px"
          />
          ${(idx1 + 1) % 2 == 0 ? `<br />` : ''}
          `
            }) : `<span style="color:#5558e8">无</span>`
          }
        </div>

        <div class="formtitle_second">处置描述</div>
        <div class="formcontent_box">${itm.handletime != null ? itm['handledescription'] : `<span style="color:#5558e8">未上传处置</span>`}</div>

        <div class="formtitle_second">上报信息</div>
        <div class="formcontent_box display_flex"
        style="width:32vw;justify-content: space-between;">
          <div>
            <span>上报单位:${itm['claimdepartmentname']}</span>
          </div>
          <div>
            <span>上报时间:${itm['handletime'] != null ? itm['handletime'] : ''}</span>
          </div>
        </div>
        <br/>
        `
      }) : '无数据'
    }
    </div >

    <div class="frombox">
      <div class="formtitle_first">其他信息</div>

      <div class="formcontent_box  display_flex">
        <span class="formcontent_box_title">信息状态:</span>
        <span>
          ${list[eventstate - 1].desc}
          ${reportinfodetail?.finishtime != null ? reportinfodetail?.finishtime : ''}
        </span>
    </div>
    <div class="formcontent_box  display_flex">
      <span class="formcontent_box_title">采纳状态:</span>
      <span>${reportinfodetail.acceptinfo == null ? "未采纳" : `已采纳(${reportinfodetail.acceptinfo.integral})`}</span>
    </div>
  </div>
  </div >
</body >
</html >
  `
  )
}

const loadfile = (info: any) => {
  let html = model(info.reportinfodetail, info.list, info.eventstate)
  let blob = new blob([html], { type: "application/msword;charset=utf-8" });
  // let blob = htmldocx.asblob(html, { orientation: "landscape" });
  filesaver.saveas(blob, "信息管理文件.doc");
}


export {
  loadfile
};

前端导出 excel文件,node-xlsx导出文件,行列合并

导出效果:

需要的依赖: node-xlsx

    "node-xlsx": "^0.23.0",

代码:

    const downxlsx = () => {
      let data = [
        [1, 222, '', '', '', ''],
        ['', 2, 3, 4, 5, 6],
        ['', 2, 3, 4, 5, 6],
        ['', 2, 3, 4, 5, 6],
        ['', 2, 3, 4, 5, 6],
        [22, 2, 3, 4, 5, 6],
      ];

      // 行列合并规则  c:col 列   r:row 行
      const range0 = { s: { c: 0, r: 0 }, e: { c: 0, r: 4 } };
      const range1 = { s: { c: 1, r: 0 }, e: { c: 5, r: 0 } };
      const sheetoptions = {
        '!merges': [range0, range1],
        // cols 列宽大小
        '!cols': [{ wch: 5 }, { wch: 10 }, { wch: 15 }, { wch: 20 }, { wch: 30 }, { wch: 50 }],
      };
      //如果不需要格式,这里的sheetoptions可以省略不写
      let result = xlsx.build([{ name: 'sheet1', data }], { sheetoptions });
      const ab = buffer.from(result, 'binary');
      const blob = new blob([ab]);
      const bloburl = url.createobjecturl(blob);
      const a = document.createelement('a');
      a.href = bloburl;
      a.download = '导出excel.xlsx';
      a.click();
      window.url.revokeobjecturl(bloburl);
    };

总结 

到此这篇关于前端导出word文件的多种方式以及导出excel文件的文章就介绍到这了,更多相关前端导出word、excel文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com