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

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

VUE動(dòng)態(tài)生成word的實(shí)現(xiàn)

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

不廢話,直接上代碼。

前端代碼:

<template> <Form ref='formValidate' :model='formValidate' :rules='ruleValidate' :label-width='110'> <FormItem label='項(xiàng)目(全稱):' prop='orgName'> <Input v-model='formValidate.orgName' placeholder='請(qǐng)輸入項(xiàng)目名稱'></Input> </FormItem> <FormItem label='申請(qǐng)人:' prop='applyName' > <Input v-model='formValidate.applyName' placeholder='請(qǐng)輸入申請(qǐng)人'></Input> </FormItem> <FormItem label='電話:' prop='applyPhone'> <Input v-model='formValidate.applyPhone' placeholder='請(qǐng)輸入電話'></Input> </FormItem> <FormItem label='生效日期:' style='float: left'> <Row><FormItem prop='startDate'> <DatePicker type='date' format='yyyy-MM-dd' placeholder='請(qǐng)選擇生效日期' v-model='formValidate.startData'></DatePicker></FormItem> </Row> </FormItem> <FormItem label='失效日期:'> <Row><FormItem prop='endDate'> <DatePicker type='date' format='yyyy-MM-dd' placeholder='請(qǐng)選擇失效日期' 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’)'>生成申請(qǐng)單</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: ’項(xiàng)目名稱不能為空!’, trigger: ’blur’ } ], applyName: [ { required: true, message: ’申請(qǐng)人不能為空!’, trigger: ’blur’ } ], applyPhone: [ { required: true, message: ’電話不能為空!’, trigger: ’change’ } ], startDate: [ { required: true, type: ’date’, message: ’請(qǐng)輸入license有效期!’, trigger: ’change’ } ], endDate: [ { required: true, type: ’date’, message: ’請(qǐng)輸入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 +’)’+’-申請(qǐng)單.doc’);document.body.appendChild(link);link.click(); } } }</script>

后臺(tái):

/** * 生成license申請(qǐng)單 */@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()+'申請(qǐng)單.doc'); resp.flushBuffer(); out = resp.getOutputStream(); byte[] buffer = new byte[512]; // 緩沖區(qū) int bytesToRead = -1; // 通過(guò)循環(huán)將讀入的Word文件的內(nèi)容輸出到瀏覽器中 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(); // 刪除臨時(shí)文件 } catch (IOException e) { e.printStackTrace(); } } }

public class ExportDoc { private static final Logger logger = LoggerFactory.getLogger(ExportDoc.class); // 針對(duì)下面這行有的報(bào)空指針,是目錄問(wèn)題,我的目錄(項(xiàng)目/src/main/java,項(xiàng)目/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'); // 調(diào)用工具類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 { // 這個(gè)地方不能使用FileWriter因?yàn)樾枰付ň幋a類型否則生成的Word文檔會(huì)因?yàn)橛袩o(wú)法識(shí)別的編碼而無(wú)法打開 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; }}

補(bǔ)充知識(shí):vue elementui 頁(yè)面預(yù)覽導(dǎo)入excel表格數(shù)據(jù)

html代碼:

<el-card class='box-card'><div slot='header' class='clearfix'><span>數(shù)據(jù)預(yù)覽</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: ’上傳文件格式錯(cuò)誤,請(qǐng)上傳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表中的數(shù)據(jù) delete worksheet[’!merges’]let A_l = worksheet[’!ref’].split(’:’)[1] //當(dāng)excel存在標(biāo)題行時(shí)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動(dòng)態(tài)生成word的實(shí)現(xiàn)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: word
相關(guān)文章:
主站蜘蛛池模板: 南京试剂|化学试剂|分析试剂|实验试剂|cas号查询-专业60年试剂销售企业 | TPU薄膜_TPU薄膜生产厂家_TPU热熔胶膜厂家定制_鑫亘环保科技(深圳)有限公司 | 都江堰招聘网-都江堰人才网 都江堰人事人才网 都江堰人才招聘网 邢台人才网_邢台招聘网_邢台123招聘【智达人才网】 | 防火阀、排烟防火阀、电动防火阀产品生产销售商-德州凯亿空调设备有限公司 | 电解抛光加工_不锈钢电解抛光_常州安谱金属制品有限公司 | DNA亲子鉴定_DNA基因检测中心官方预约平台-严选好基因网 | 旗帜网络笔记-免费领取《旗帜网络笔记》电子书 | 吊篮式|移动式冷热冲击试验箱-二槽冷热冲击试验箱-广东科宝 | 自动记录数据电子台秤,记忆储存重量电子桌称,设定时间记录电子秤-昆山巨天 | POS机办理_个人pos机免费领取-银联pos机申请首页| 数显水浴恒温振荡器-分液漏斗萃取振荡器-常州市凯航仪器有限公司 | 单螺旋速冻机-双螺旋-流态化-隧道式-食品速冻机厂家-广州冰泉制冷 | 航空障碍灯_高中低光强航空障碍灯_民航许可认证航空警示灯厂家-东莞市天翔航天科技有限公司 | 网优资讯-为循环资源、大宗商品、工业服务提供资讯与行情分析的数据服务平台 | 深圳高新投三江工业消防解决方案提供厂家_服务商_园区智慧消防_储能消防解决方案服务商_高新投三江 | 综合管廊模具_生态,阶梯护坡模具_检查井模具制造-致宏模具厂家 | 水成膜泡沫灭火剂_氟蛋白泡沫液_河南新乡骏华消防科技厂家 | 层流手术室净化装修-检验科ICU改造施工-华锐净化工程-特殊科室建设厂家 | 一体化净水器_一体化净水设备_一体化水处理设备-江苏旭浩鑫环保科技有限公司 | 【中联邦】增稠剂_增稠粉_水性增稠剂_涂料增稠剂_工业增稠剂生产厂家 | 阳光模拟试验箱_高低温试验箱_高低温冲击试验箱_快速温变试验箱|东莞市赛思检测设备有限公司 | 精密模具加工制造 - 富东懿 | 仿古瓦,仿古金属瓦,铝瓦,铜瓦,铝合金瓦-西安东申景观艺术工程有限公司 | 深圳标识制作公司-标识标牌厂家-深圳广告标识制作-玟璟广告-深圳市玟璟广告有限公司 | 仿古瓦,仿古金属瓦,铝瓦,铜瓦,铝合金瓦-西安东申景观艺术工程有限公司 | 蓄电池回收,ups电池后备电源回收,铅酸蓄电池回收,机房电源回收-广州益夫铅酸电池回收公司 | 高速混合机_锂电混合机_VC高效混合机-无锡鑫海干燥粉体设备有限公司 | 一体化污水处理设备-一体化净水设备-「山东梦之洁水处理」 | 食品无尘净化车间,食品罐装净化车间,净化车间配套风淋室-青岛旭恒洁净技术有限公司 | 好杂志网-首页| 电磁辐射仪-电磁辐射检测仪-pm2.5检测仪-多功能射线检测仪-上海何亦仪器仪表有限公司 | 切铝机-数控切割机-型材切割机-铝型材切割机-【昆山邓氏精密机械有限公司】 | 视频直播 -摄影摄像-视频拍摄-直播分发 | 国际高中-国际学校-一站式择校服务-远播国际教育 | 专业甜品培训学校_广东糖水培训_奶茶培训_特色小吃培训_广州烘趣甜品培训机构 | 工业rfid读写器_RFID工业读写器_工业rfid设备厂商-ANDEAWELL | 模切之家-专注服务模切行业的B2B平台! | 连续油炸机,全自动油炸机,花生米油炸机-烟台茂源食品机械制造有限公司 | 上海新光明泵业制造有限公司-电动隔膜泵,气动隔膜泵,卧式|立式离心泵厂家 | 车牌识别道闸_停车场收费系统_人脸识别考勤机_速通门闸机_充电桩厂家_中全清茂官网 | 合肥角钢_合肥槽钢_安徽镀锌管厂家-昆瑟商贸有限公司 |