电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

VUE動態生成word的實現

瀏覽:119日期:2022-06-11 18:00:15

不廢話,直接上代碼。

前端代碼:

<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- 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.resultconst fixedData = this.fixdata(data)const workbook = XLSX.read(btoa(fixedData), { type: ’base64’ })const firstSheetName = workbook.SheetNames[0] // 第一張表 sheet1const worksheet = workbook.Sheets[firstSheetName] // 讀取sheet1表中的數據 delete worksheet[’!merges’]let A_l = worksheet[’!ref’].split(’:’)[1] //當excel存在標題行時worksheet[’!ref’] = `A2:${A_l}`const tableTitle = firstSheetNameconst 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的實現就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: word
相關文章:
主站蜘蛛池模板: 真空泵维修保养,普发,阿尔卡特,荏原,卡西亚玛,莱宝,爱德华干式螺杆真空泵维修-东莞比其尔真空机电设备有限公司 | 广州昊至泉水上乐园设备有限公司| 苏州工作服定做-工作服定制-工作服厂家网站-尺品服饰科技(苏州)有限公司 | 苏州防水公司_厂房屋面外墙防水_地下室卫生间防水堵漏-苏州伊诺尔防水工程有限公司 | 泵阀展|阀门展|水泵展|流体机械展 -2025上海国际泵管阀展览会flowtech china | 行业分析:提及郑州火车站附近真有 特殊按摩 ?2025实地踩坑指南 新手如何避坑不踩雷 | 全自动变压器变比组别测试仪-手持式直流电阻测试仪-上海来扬电气 | 铝箔袋,铝箔袋厂家,东莞铝箔袋,防静电铝箔袋,防静电屏蔽袋,防静电真空袋,真空袋-东莞铭晋让您的产品与众不同 | 武汉高温老化房,恒温恒湿试验箱,冷热冲击试验箱-武汉安德信检测设备有限公司 | 手板_手板模型制作_cnc手板加工厂-东莞天泓 | 深圳美安可自动化设备有限公司,喷码机,定制喷码机,二维码喷码机,深圳喷码机,纸箱喷码机,东莞喷码机 UV喷码机,日期喷码机,鸡蛋喷码机,管芯喷码机,管内壁喷码机,喷码机厂家 | 防水试验机_防水测试设备_防水试验装置_淋雨试验箱-广州岳信试验设备有限公司 | J.S.Bach 圣巴赫_高端背景音乐系统_官网| 开锐教育-学历提升-职称评定-职业资格培训-积分入户 | 防爆电机生产厂家,YBK3电动机,YBX3系列防爆电机,YBX4节防爆电机--河南省南洋防爆电机有限公司 | 纯化水设备-纯水设备-超纯水设备-[大鹏水处理]纯水设备一站式服务商-东莞市大鹏水处理科技有限公司 | NMRV减速机|铝合金减速机|蜗轮蜗杆减速机|NMRV减速机厂家-东莞市台机减速机有限公司 | 真空包装机-诸城市坤泰食品机械有限公司 | 高低温试验房-深圳高低温湿热箱-小型高低温冲击试验箱-爱佩试验设备 | 对照品_中药对照品_标准品_对照药材_「格利普」高纯中药标准品厂家-成都格利普生物科技有限公司 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库 | 东莞ERP软件_广州云ERP_中山ERP_台湾工厂erp系统-广东顺景软件科技有限公司 | 经济师考试_2025中级经济师报名时间_报名入口_考试时间_华课网校经济师培训网站 | 活动策划,舞台搭建,活动策划公司-首选美湖上海活动策划公司 | CNC机加工-数控加工-精密零件加工-ISO认证厂家-鑫创盟 | 铝单板_铝窗花_铝单板厂家_氟碳包柱铝单板批发价格-佛山科阳金属 | 悬浮拼装地板_幼儿园_篮球场_悬浮拼接地板-山东悬浮拼装地板厂家 | 杭州可当科技有限公司—流量卡_随身WiFi_AI摄像头一站式解决方案 | 金属管浮子流量计_金属转子流量计厂家-淮安润中仪表科技有限公司 | 碳纤维复合材料制品生产定制工厂订制厂家-凯夫拉凯芙拉碳纤维手机壳套-碳纤维雪茄盒外壳套-深圳市润大世纪新材料科技有限公司 | 精准猎取科技资讯,高效阅读科技新闻_科技猎 | 废气处理_废气处理设备_工业废气处理_江苏龙泰环保设备制造有限公司 | 耐力板-PC阳光板-PC板-PC耐力板 - 嘉兴赢创实业有限公司 | 烘箱-工业烘箱-工业电炉-实验室干燥箱 - 苏州华洁烘箱制造有限公司 | SDI车窗夹力测试仪-KEMKRAFT方向盘测试仪-上海爱泽工业设备有限公司 | 生产加气砖设备厂家很多,杜甫机械加气砖设备价格公道 | 定制防伪标签_防伪标签印刷_防伪标签厂家-510品保防伪网 | 清洁设备_洗地机/扫地机厂家_全自动洗地机_橙犀清洁设备官网 | 电子厂招聘_工厂招聘_普工招聘_小时工招聘信息平台-众立方招工网 | 非甲烷总烃分析仪|环控百科 | 广州展台特装搭建商|特装展位设计搭建|展会特装搭建|特装展台制作设计|展览特装公司 | 掺铥光纤放大器-C/L波段光纤放大器-小信号光纤放大器-合肥脉锐光电技术有限公司 |