SoFunction
Updated on 2025-04-03

Implementation of VUE dynamically generated word

Don't talk nonsense, just upload the code.

Front-end code:

<template>
  <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="110">
    <FormItem label="Project (full name):" prop="orgName">
      <Input v-model="" placeholder="Please enter the project name"></Input>
    </FormItem>
    <FormItem label="applicant:" prop="applyName" >
      <Input v-model="" placeholder="Please enter the applicant"></Input>
    </FormItem>
    <FormItem label="Telephone:" prop="applyPhone">
      <Input v-model="" placeholder="Please enter your phone number"></Input>
    </FormItem>
    <FormItem label="Effective Date:" style="float: left">
      <Row>
        <FormItem prop="startDate">
          <DatePicker type="date" format="yyyy-MM-dd" placeholder="Please select the effective date" v-model=""></DatePicker>
        </FormItem>
      </Row>
    </FormItem>
    <FormItem label="Expiration date:">
      <Row>
        <FormItem prop="endDate">
          <DatePicker type="date" format="yyyy-MM-dd" placeholder="Please select the expiration date" v-model=""></DatePicker>
        </FormItem>
      </Row>
    </FormItem>
    <FormItem label="Remark:" prop="vmemo">
      <Input v-model="" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="Remark"></Input>
    </FormItem>
    <FormItem>
      <Button type="primary" @click="handleSubmit('formValidate')">Generate an application form</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: 'The project name cannot be empty!  ', trigger: 'blur' }
          ],
          applyName: [
            { required: true, message: 'Applicants cannot be empty!  ', trigger: 'blur' }
          ],
          applyPhone: [
            { required: true, message: 'The phone cannot be empty!  ', trigger: 'change' }
          ],
          startDate: [
            { required: true, type: 'date', message: 'Please enter the validity period of license!  ', trigger: 'change' }
          ],
          endDate: [
            { required: true, type: 'date', message: 'Please enter the validity period of license!  ', trigger: 'change' }
          ],
        }
      }
    },
    methods: {
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            axios({
              method: 'post',
              url: this.$,
              data: ,
              responseType: 'blob'
            }).then(res => {
              ();
            });
          }
        });
      },
      download (data) {
        if (!data) {
          return
        }
        let url = (new Blob([data]))
        let link = ('a');
         = 'none';
         = url;
        ('download', +'('+  +')'+'-Application form.doc');
        (link);
        ();
      }
    }
  }
</script>

Backstage:

/**
  * Generate license application form
  */
@RequestMapping(value = "/note", method = )
public void requestNote(@RequestBody LicenseRequestNoteModel noteModel, HttpServletRequest req, HttpServletResponse resp) {
  File file = null;
  InputStream fin = null;
  ServletOutputStream out = null;
  try {
    ("utf-8");
    file = (noteModel, req, resp);
    fin = new FileInputStream(file);
    ("utf-8");
    ("application/octet-stream");
    ("Content-Disposition", "attachment;filename="+ ()+"Apply for.doc");
    ();
    out = ();
    byte[] buffer = new byte[512]; // Buffer    int bytesToRead = -1;
    // Loop to output the content of the read Word file to the browser    while ((bytesToRead = (buffer)) != -1) {
      (buffer, 0, bytesToRead);
    }
 
  } catch (Exception e) {
    ();
  } finally {
    try {
      if (fin != null) ();
      if (out != null) ();
      if (file != null) (); // Delete temporary files    } catch (IOException e) {
      ();
    }
  }
 
}
public class ExportDoc {
  private static final Logger logger = ();
  // For some empty pointers in the following line, it is a directory problem. My directory (project/src/main/java, project/src/main/resources), you can also specify folders by yourself in this section.  private static final String templateFolder = ().getResource("/").getPath();
  private static Configuration configuration = null;
  private static Map<String, Template> allTemplates = null;
 
  static {
    configuration = new Configuration();
    ("utf-8");
 
    allTemplates = new HashedMap();
    try {
      (new File(templateFolder));
      ("resume", (""));
    } catch (IOException e) {
      ();
      throw new RuntimeException(e);
    }
  }
 
 
  public static File createWord(LicenseRequestNoteModel noteModel, HttpServletRequest req, HttpServletResponse resp) throws Exception {
    File file = null;
 
    ("utf-8");
    // Call the createDoc method of the tool class WordGenerator to generate Word documents    file = createDoc(getData(noteModel), "resume");
    return file;
  }
 
 
  public static File createDoc(Map<?, ?> dataMap, String type) {
    String name = "temp" + (int) (() * 100000) + ".doc";
    File f = new File(name);
    Template t = (type);
    try {
      // This place cannot be used as FileWriter because you need to specify the encoding type, otherwise the generated Word document will not be opened due to unrecognized encoding.      Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
      (dataMap, w);
      ();
    } catch (Exception ex) {
      ();
      throw new RuntimeException(ex);
    }
    return f;
  }
 
 
  private static Map<String, Object> getData(LicenseRequestNoteModel noteModel) throws Exception {
 
    Map<String, Object> map = new HashedMap();
    ("orgName", ());
    ("applyName", ());
    ("applyPhone", ());
    ("ncVersion", ());
    ("environment", ());
    ("applyType", ());
 
    ("mac", ());
    ("ip", ());
    ("startData", (()));
    ("endData", (()));
    ("hostName", ());
    ("vmemo", ());
    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) {
     = projectName;
  }
 
  public String getApplyName() {
    return applyName;
  }
 
  public void setApplyName(String applyName) {
     = applyName;
  }
 
  public String getApplyPhone() {
    return applyPhone;
  }
 
  public void setApplyPhone(String applyPhone) {
     = applyPhone;
  }
 
  public String getNcVersionModel() {
    return ncVersionModel;
  }
 
  public void setNcVersionModel(String ncVersionModel) {
     = ncVersionModel;
  }
 
  public String getEnvironmentModel() {
    return environmentModel;
  }
 
  public void setEnvironmentModel(String environmentModel) {
     = environmentModel;
  }
 
  public String getApplyTypeModel() {
    return applyTypeModel;
  }
 
  public void setApplyTypeModel(String applyTypeModel) {
     = applyTypeModel;
  }
 
  public Date getStartData() {
    return startData;
  }
 
  public void setStartData(Date startData) {
     = startData;
  }
 
  public Date getEndData() {
    return endData;
  }
 
  public void setEndData(Date endData) {
     = endData;
  }
 
  public String[] getHostName() {
    return hostName;
  }
 
  public String getHostNames() {
    return (,",");
  }
  public void setHostName(String[] hostName) {
     = hostName;
  }
 
  public String getVmemo() {
    return vmemo;
  }
 
  public void setVmemo(String vmemo) {
     = vmemo;
  }
 
  public String getApplyMAC() {
    return applyMAC;
  }
 
  public void setApplyMAC(String applyMAC) {
     = applyMAC;
  }
 
  public String getApplyIP() {
    return applyIP;
  }
 
  public void setApplyIP(String applyIP) {
     = applyIP;
  }
}

Supplementary knowledge:vue elementui page preview import excel table data

html code:

<el-card class="box-card">
<div slot="header" class="clearfix">
<span>Data preview</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 code:

import XLSX from 'xlsx'
 
data() {
  return {
    tableData: '', 
    tableHeader: '' 
  }
},
mounted: {
  ('el-upload__input')[0].setAttribute('accept', '.xlsx, .xls')
  ('el-upload__input')[0].onchange = (e) => {
    const files =  itemFile = files[0] // only use files[0]if (!itemFile) 
    return (itemFile)
  }
},
methods: {
  generateDate({ tableTitle, header, results }) {
     = tableTitle
     = results
     = header
  },
  handleDrop(e) {
    ()
    ()
    const files = 
    if ( !== 1) {
      this.$('Only support uploading one file!')
      return
    }
    const itemFile = files[0] // only use files[0]
    (itemFile)
    ()
    ()
  },
  handleDragover(e) {
    ()
    ()
     = 'copy'
  },
  readerData(itemFile) {
    if (('.')[1] != 'xls' && ('.')[1] != 'xlsx') {
      this.$message({message: 'The upload file format is wrong, please upload xls and xlsx files!  ',type: 'warning'});
     } else {
      const reader = new FileReader()
       = e => {
        const data = 
        const fixedData = (data)
        const workbook = (btoa(fixedData), { type: 'base64' })
        const firstSheetName = [0] // The first table sheet1        const worksheet = [firstSheetName] // Read the data in the sheet1 table delete worksheet['!merges']let A_l = worksheet['!ref'].split(':')[1] //When excel has the title line        worksheet['!ref'] = `A2:${A_l}`
        const tableTitle = firstSheetName
        const header = this.get_header_row(worksheet)
        const results = .sheet_to_json(worksheet)
        ({ tableTitle, header, results })
       }
        (itemFile)
     }
  },
  fixdata(data) {
    let o = ''
    let l = 0
    const w = 10240
    for (; l <  / w; ++l) 
    o += (null, new Uint8Array((l * w, l * w + w)))
    o += (null, new Uint8Array((l * w)))
    return o
  },
  get_header_row(sheet) {
    const headers = []
    const range = .decode_range(sheet['!ref'])
    let Cconst R =  /* start in the first row */
    for (C = ; C <= ; ++C) { /* walk every column in the range */
      var cell = sheet[.encode_cell({ c: C, r: R })] /* find the cell in the first row */
      var hdr = 'UNKNOWN ' + C // <-- replace with your desired defaultif (cell && ) 
      hdr = .format_cell(cell)
      (hdr)
    }
    return headers
  }

The above VUE dynamic word implementation is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.