VUE动态生成word的实现 程序员文章站 2022-03-27 19:41:40 不废话,直接上代码。前端代码: 不废话,直接上代码。 前端代码: <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的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。 相关标签: VUE 生成 word 上一篇: ai怎么绘制不规则的格子图标? ai表格的画法 下一篇: 奔主题:京东双十一红包主会场入口 天猫双十一11红包津贴使用规范 推荐阅读 vue中使用async、await和promise实现异步API的同步调用 c#使用简单工厂模式实现生成html文件的封装类分享 vue实现员工信息录入功能的方法 LINUX下PHP程序实现WORD文件转化为PDF文件的方法 Spring boot + mybatis + Vue.js + ElementUI 实现数据的增删改查实例代码(一) ASP.NET实现根据URL生成网页缩略图的方法 利用Aspose.Word控件实现Word文档的操作 .net使用Aspose.Words进行Word替换操作的实现代码 java 动态加载的实现代码 Java实现的动态数字时钟功能示例【显示世界时间】