VUE 동적 생성word 구현
프런트엔드 코드:
<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의 실현은 바로 편집자가 여러분에게 공유한 모든 내용입니다. 여러분께 참고가 되고 저희를 많이 사랑해 주시기 바랍니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
VUE 기반 장치가 PC인지 모바일 포트인지 판단실제 개발 과정에서 자주 발생하는 수요는 현재 웹 페이지에 로그인한 장치가 PC인지 이동인지를 판단하고 PC 측과 모바일 측이 서로 다른 웹 내용을 표시하도록 요구하는 것이다. 그러면 현재 로그인 장치에 대한 판단이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.