VUE动态生成word的实现


Posted in Javascript onJuly 26, 2020

不废话,直接上代码。

前端代码:

<template>
  <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="110">
    <FormItem label="项目(全称):" prop="orgName">
      <Input v-model="formValidate.orgName" placeholder="请输入项目名称"></Input>
    </FormItem>
    <FormItem label="申请人:" prop="applyName" >
      <Input v-model="formValidate.applyName" placeholder="请输入申请人"></Input>
    </FormItem>
    <FormItem label="电话:" prop="applyPhone">
      <Input v-model="formValidate.applyPhone" placeholder="请输入电话"></Input>
    </FormItem>
    <FormItem label="生效日期:" style="float: left">
      <Row>
        <FormItem prop="startDate">
          <DatePicker type="date" format="yyyy-MM-dd" placeholder="请选择生效日期" v-model="formValidate.startData"></DatePicker>
        </FormItem>
      </Row>
    </FormItem>
    <FormItem label="失效日期:">
      <Row>
        <FormItem prop="endDate">
          <DatePicker type="date" format="yyyy-MM-dd" placeholder="请选择失效日期" v-model="formValidate.endData"></DatePicker>
        </FormItem>
      </Row>
    </FormItem>
    <FormItem label="备注:" prop="vmemo">
      <Input v-model="formValidate.vmemo" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="备注"></Input>
    </FormItem>
    <FormItem>
      <Button type="primary" @click="handleSubmit('formValidate')">生成申请单</Button>
    </FormItem>
  </Form>
</template>
<script>
  import axios from 'axios';
  export default {
    data () {
      return {
        formValidate: {
          orgName: '',
          applyName: '',
          applyPhone: '',
          startDate: '',
          endDate: '',
          vmemo:''
        },
        ruleValidate: {
          orgName: [
            { required: true, message: '项目名称不能为空!', trigger: 'blur' }
          ],
          applyName: [
            { required: true, message: '申请人不能为空!', trigger: 'blur' }
          ],
          applyPhone: [
            { required: true, message: '电话不能为空!', trigger: 'change' }
          ],
          startDate: [
            { required: true, type: 'date', message: '请输入license有效期!', trigger: 'change' }
          ],
          endDate: [
            { required: true, type: 'date', message: '请输入license有效期!', trigger: 'change' }
          ],
        }
      }
    },
    methods: {
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            axios({
              method: 'post',
              url: this.$store.getters.requestNoteUrl,
              data: this.formValidate,
              responseType: 'blob'
            }).then(res => {
              this.download(res.data);
            });
          }
        });
      },
      download (data) {
        if (!data) {
          return
        }
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', this.formValidate.orgName+'('+ this.formValidate.applyName +')'+'-申请单.doc');
        document.body.appendChild(link);
        link.click();
      }
    }
  }
</script>

后台:

/**
 * 生成license申请单
 */
@RequestMapping(value = "/note", method = RequestMethod.POST)
public void requestNote(@RequestBody LicenseRequestNoteModel noteModel, HttpServletRequest req, HttpServletResponse resp) {
  File file = null;
  InputStream fin = null;
  ServletOutputStream out = null;
  try {
    req.setCharacterEncoding("utf-8");
    file = ExportDoc.createWord(noteModel, req, resp);
    fin = new FileInputStream(file);
    resp.setCharacterEncoding("utf-8");
    resp.setContentType("application/octet-stream");
    resp.addHeader("Content-Disposition", "attachment;filename="+ noteModel.getOrgName()+"申请单.doc");
    resp.flushBuffer();
    out = resp.getOutputStream();
    byte[] buffer = new byte[512]; // 缓冲区
    int bytesToRead = -1;
    // 通过循环将读入的Word文件的内容输出到浏览器中
    while ((bytesToRead = fin.read(buffer)) != -1) {
      out.write(buffer, 0, bytesToRead);
    }
 
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    try {
      if (fin != null) fin.close();
      if (out != null) out.close();
      if (file != null) file.delete(); // 删除临时文件
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 
}
public class ExportDoc {
  private static final Logger logger = LoggerFactory.getLogger(ExportDoc.class);
  // 针对下面这行有的报空指针,是目录问题,我的目录(项目/src/main/java,项目/src/main/resources),这块也可以自己指定文件夹
  private static final String templateFolder = ExportDoc.class.getClassLoader().getResource("/").getPath();
  private static Configuration configuration = null;
  private static Map<String, Template> allTemplates = null;
 
  static {
    configuration = new Configuration();
    configuration.setDefaultEncoding("utf-8");
 
    allTemplates = new HashedMap();
    try {
      configuration.setDirectoryForTemplateLoading(new File(templateFolder));
      allTemplates.put("resume", configuration.getTemplate("licenseApply.ftl"));
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
 
 
  public static File createWord(LicenseRequestNoteModel noteModel, HttpServletRequest req, HttpServletResponse resp) throws Exception {
    File file = null;
 
    req.setCharacterEncoding("utf-8");
    // 调用工具类WordGenerator的createDoc方法生成Word文档
    file = createDoc(getData(noteModel), "resume");
    return file;
  }
 
 
  public static File createDoc(Map<?, ?> dataMap, String type) {
    String name = "temp" + (int) (Math.random() * 100000) + ".doc";
    File f = new File(name);
    Template t = allTemplates.get(type);
    try {
      // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
      Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
      t.process(dataMap, w);
      w.close();
    } catch (Exception ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
    return f;
  }
 
 
  private static Map<String, Object> getData(LicenseRequestNoteModel noteModel) throws Exception {
 
    Map<String, Object> map = new HashedMap();
    map.put("orgName", noteModel.getOrgName());
    map.put("applyName", noteModel.getApplyName());
    map.put("applyPhone", noteModel.getApplyPhone());
    map.put("ncVersion", noteModel.getNcVersionModel());
    map.put("environment", noteModel.getEnvironmentModel());
    map.put("applyType", noteModel.getApplyTypeModel());
 
    map.put("mac", GetLicenseSource.getMacId());
    map.put("ip", GetLicenseSource.getLocalIP());
    map.put("startData", DateUtil.Date(noteModel.getStartData()));
    map.put("endData", DateUtil.Date(noteModel.getEndData()));
    map.put("hostName", noteModel.getHostNames());
    map.put("vmemo", noteModel.getVmemo());
    return map;
  }
 
}
public class LicenseRequestNoteModel{
  private String orgName = null;
 
  private String applyName = null;
 
  private String applyPhone = null;
  
  private String ncVersionModel= null;
 
  private String environmentModel= null;
 
  private String applyTypeModel= null;
 
  @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  private Date startData= null;
 
  @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  private Date endData= null;
 
  private String[] hostName= null;
 
  private String vmemo= null;
 
  private String applyMAC= null;
 
  private String applyIP= null;
 
  public String getOrgName() {
    return orgName;
  }
 
  public void setOrgName(String projectName) {
    this.orgName = projectName;
  }
 
  public String getApplyName() {
    return applyName;
  }
 
  public void setApplyName(String applyName) {
    this.applyName = applyName;
  }
 
  public String getApplyPhone() {
    return applyPhone;
  }
 
  public void setApplyPhone(String applyPhone) {
    this.applyPhone = applyPhone;
  }
 
  public String getNcVersionModel() {
    return ncVersionModel;
  }
 
  public void setNcVersionModel(String ncVersionModel) {
    this.ncVersionModel = ncVersionModel;
  }
 
  public String getEnvironmentModel() {
    return environmentModel;
  }
 
  public void setEnvironmentModel(String environmentModel) {
    this.environmentModel = environmentModel;
  }
 
  public String getApplyTypeModel() {
    return applyTypeModel;
  }
 
  public void setApplyTypeModel(String applyTypeModel) {
    this.applyTypeModel = applyTypeModel;
  }
 
  public Date getStartData() {
    return startData;
  }
 
  public void setStartData(Date startData) {
    this.startData = startData;
  }
 
  public Date getEndData() {
    return endData;
  }
 
  public void setEndData(Date endData) {
    this.endData = endData;
  }
 
  public String[] getHostName() {
    return hostName;
  }
 
  public String getHostNames() {
    return StringUtils.join(this.hostName,",");
  }
  public void setHostName(String[] hostName) {
    this.hostName = hostName;
  }
 
  public String getVmemo() {
    return vmemo;
  }
 
  public void setVmemo(String vmemo) {
    this.vmemo = vmemo;
  }
 
  public String getApplyMAC() {
    return applyMAC;
  }
 
  public void setApplyMAC(String applyMAC) {
    this.applyMAC = applyMAC;
  }
 
  public String getApplyIP() {
    return applyIP;
  }
 
  public void setApplyIP(String applyIP) {
    this.applyIP = applyIP;
  }
}

补充知识:vue elementui 页面预览导入excel表格数据

html代码:

<el-card class="box-card">
<div slot="header" class="clearfix">
<span>数据预览</span>
</div>
<div class="text item">
<el-table :data="tableData" border highlight-current-row style="width: 100%;">
<el-table-column :label="tableTitle" >
<el-table-column min-width="150" v-for='item tableHeader' :prop="item" :label="item" :key='item'>
</el-table-column>
</el-table-column>
</el-table>
</div>
</el-card>

js代码:

import XLSX from 'xlsx'
 
data() {
  return {
    tableData: '', 
    tableHeader: '' 
  }
},
mounted: {
  document.getElementsByClassName('el-upload__input')[0].setAttribute('accept', '.xlsx, .xls')
  document.getElementsByClassName('el-upload__input')[0].onchange = (e) => {
    const files = e.target.filesconst itemFile = files[0] // only use files[0]if (!itemFile) 
    return this.readerData(itemFile)
  }
},
methods: {
  generateDate({ tableTitle, header, results }) {
    this.tableTitle = tableTitle
    this.tableData = results
    this.tableHeader = header
  },
  handleDrop(e) {
    e.stopPropagation()
    e.preventDefault()
    const files = e.dataTransfer.files
    if (files.length !== 1) {
      this.$message.error('Only support uploading one file!')
      return
    }
    const itemFile = files[0] // only use files[0]
    this.readerData(itemFile)
    e.stopPropagation()
    e.preventDefault()
  },
  handleDragover(e) {
    e.stopPropagation()
    e.preventDefault()
    e.dataTransfer.dropEffect = 'copy'
  },
  readerData(itemFile) {
    if (itemFile.name.split('.')[1] != 'xls' && itemFile.name.split('.')[1] != 'xlsx') {
      this.$message({message: '上传文件格式错误,请上传xls、xlsx文件!',type: 'warning'});
     } else {
      const reader = new FileReader()
      reader.onload = e => {
        const data = e.target.result
        const fixedData = this.fixdata(data)
        const workbook = XLSX.read(btoa(fixedData), { type: 'base64' })
        const firstSheetName = workbook.SheetNames[0] // 第一张表 sheet1
        const worksheet = workbook.Sheets[firstSheetName] // 读取sheet1表中的数据       delete worksheet['!merges']let A_l = worksheet['!ref'].split(':')[1] //当excel存在标题行时
        worksheet['!ref'] = `A2:${A_l}`
        const tableTitle = firstSheetName
        const header = this.get_header_row(worksheet)
        const results = XLSX.utils.sheet_to_json(worksheet)
        this.generateDate({ tableTitle, header, results })
       }
        reader.readAsArrayBuffer(itemFile)
     }
  },
  fixdata(data) {
    let o = ''
    let l = 0
    const w = 10240
    for (; l < data.byteLength / w; ++l) 
    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
    return o
  },
  get_header_row(sheet) {
    const headers = []
    const range = XLSX.utils.decode_range(sheet['!ref'])
    let Cconst R = range.s.r /* start in the first row */
    for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
      var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */
      var hdr = 'UNKNOWN ' + C // <-- replace with your desired defaultif (cell && cell.t) 
      hdr = XLSX.utils.format_cell(cell)
      headers.push(hdr)
    }
    return headers
  }

以上这篇VUE动态生成word的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
CSS鼠标响应事件经过、移动、点击示例介绍
Sep 04 Javascript
jquery mobile的触控点击事件会多次触发问题的解决方法
May 08 Javascript
js匿名函数的调用示例(形式多种多样)
Aug 20 Javascript
angular简介和其特点介绍
Jan 29 Javascript
javascript实用方法总结
Feb 06 Javascript
javascript实现实时输出当前的时间
Apr 27 Javascript
基于BootStrap Metronic开发框架经验小结【九】实现Web页面内容的打印预览和保存操作
May 12 Javascript
JS仿hao123导航页面图片轮播效果
Sep 01 Javascript
jQuery常见的选择器及用法介绍
Dec 20 Javascript
javascript+HTML5 canvas绘制时钟功能示例
May 15 Javascript
Vue实现push数组并删除的例子
Nov 01 Javascript
详解vue-flickity的fullScreen功能实现
Apr 07 Javascript
Element Dialog对话框的使用示例
Jul 26 #Javascript
在vue中使用防抖函数组件操作
Jul 26 #Javascript
Vue 中使用lodash对事件进行防抖和节流操作
Jul 26 #Javascript
浅谈vue中document.getElementById()拿到的是原值的问题
Jul 26 #Javascript
关于vue 结合原生js 解决echarts resize问题
Jul 26 #Javascript
Element Tooltip 文字提示的使用示例
Jul 26 #Javascript
Element Popover 弹出框的使用示例
Jul 26 #Javascript
You might like
浅析使用Turck-mmcache编译来加速、优化PHP代码
2013/06/20 PHP
php+mysql结合Ajax实现点赞功能完整实例
2015/01/30 PHP
PHP使用array_fill定义多维数组的方法
2015/03/18 PHP
php实现随机生成易于记忆的密码
2015/06/19 PHP
PHP输出缓冲控制Output Control系列函数详解
2015/07/02 PHP
基于Jquery的$.cookie()实现跨越页面tabs导航实现代码
2011/03/03 Javascript
javascript实现tabs选项卡切换效果(扩展版)
2013/03/19 Javascript
JS实现随机化快速排序的实例代码
2013/08/01 Javascript
利用js制作html table分页示例(js实现分页)
2014/04/25 Javascript
jQuery控制元素显示、隐藏、切换、滑动的方法总结
2015/04/16 Javascript
jQuery实现高亮显示网页关键词的方法
2015/08/07 Javascript
浅析Bootstrap表格的使用
2016/06/23 Javascript
关于Vue.js 2.0的Vuex 2.0 你需要更新的知识库
2016/11/30 Javascript
解析jquery easyui tree异步加载子节点问题
2017/03/08 Javascript
node.js调用Chrome浏览器打开链接地址的方法
2017/05/17 Javascript
vue使用keep-alive实现数据缓存不刷新
2017/10/21 Javascript
NodeJs form-data格式传输文件的方法
2017/12/13 NodeJs
element-ui 关于获取select 的label值方法
2018/08/24 Javascript
Vue监听事件实现计数点击依次增加的方法
2018/09/26 Javascript
vue实现简单瀑布流布局
2020/05/28 Javascript
详解JavaScript匿名函数和闭包
2020/07/10 Javascript
[01:24]2014DOTA2 TI第二日 YYF表示这届谁赢都有可能
2014/07/11 DOTA
Python字符串通过'+'和join函数拼接新字符串的性能测试比较
2019/03/05 Python
python中时间、日期、时间戳的转换的实现方法
2019/07/06 Python
python实现爬虫抓取小说功能示例【抓取金庸小说】
2019/08/09 Python
Python和Sublime整合过程图示
2019/12/25 Python
提升python处理速度原理及方法实例
2019/12/25 Python
Python中的Cookie模块如何使用
2020/06/04 Python
Bibloo罗马尼亚网站:女装、男装、童装及鞋子和配饰
2019/07/20 全球购物
一加手机美国官方网站:OnePlus美国
2019/09/19 全球购物
应届生求职信范文
2014/05/26 职场文书
大型主题婚礼活动策划方案
2014/09/15 职场文书
春季运动会开幕词
2015/01/28 职场文书
七一建党节慰问信
2015/02/14 职场文书
2015年节能减排工作总结
2015/05/14 职场文书
Python获取字典中某个key的value
2022/04/13 Python