最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2020年07月26日 14:51:15   作者:LeasonSong  
這篇文章主要介紹了VUE動(dòng)態(tài)生成word的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

不廢話,直接上代碼。

前端代碼:

<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;
    // 通過循環(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)空指針,是目錄問題,我的目錄(項(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法識(shí)別的編碼而無法打開
      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ù)覽導(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-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: '上傳文件格式錯(cuò)誤,請(qǐng)上傳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表中的數(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 = 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動(dòng)態(tài)生成word的實(shí)現(xiàn)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • vue.js中proxyTable 轉(zhuǎn)發(fā)請(qǐng)求的實(shí)現(xiàn)方法

    vue.js中proxyTable 轉(zhuǎn)發(fā)請(qǐng)求的實(shí)現(xiàn)方法

    今天小編就為大家分享一篇vue.js中proxyTable 轉(zhuǎn)發(fā)請(qǐng)求的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-09-09
  • 關(guān)于element ui中el-cascader的使用方式

    關(guān)于element ui中el-cascader的使用方式

    這篇文章主要介紹了關(guān)于element ui中el-cascader的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • webpack4+express+mongodb+vue實(shí)現(xiàn)增刪改查的示例

    webpack4+express+mongodb+vue實(shí)現(xiàn)增刪改查的示例

    這篇文章主要介紹了webpack4+express+mongodb+vue 實(shí)現(xiàn)增刪改查的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-11-11
  • Vue Router中應(yīng)用中間件的方法

    Vue Router中應(yīng)用中間件的方法

    這篇文章主要介紹了Vue Router中應(yīng)用中間件的方法,文中講解非常細(xì)致,幫助大家更好的理解和學(xué)習(xí)vue router,感興趣的朋友可以了解下
    2020-08-08
  • Vue3 AST解析器-源碼解析

    Vue3 AST解析器-源碼解析

    這篇文章我們從 ast 生成時(shí)調(diào)用的 baseParse 函數(shù)分析,再到 baseParse 返回 createRoot 的調(diào)用結(jié)果,一直到細(xì)化的講解了 parseChildren 解析子節(jié)點(diǎn)函數(shù)中的其中某一個(gè)具體解析器的執(zhí)行過程。最后通過一個(gè)簡單模板舉例,需要的朋友可以參考下
    2021-09-09
  • vue中@click和@click.native.prevent的區(qū)別

    vue中@click和@click.native.prevent的區(qū)別

    這篇文章主要介紹了vue中@click和@click.native.prevent的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • rollup打包vue組件并發(fā)布到npm的方法

    rollup打包vue組件并發(fā)布到npm的方法

    這篇文章主要介紹了rollup打包vue組件并發(fā)布到npm,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-05-05
  • vue中組件之間相互傳值的6種方法小結(jié)

    vue中組件之間相互傳值的6種方法小結(jié)

    Vue.js?中組件間通信的方法有很多種,這篇文章主要為大家詳細(xì)介紹了6種常見的直接或間接的組件傳值方式,有需要的小伙伴可以參考一下
    2024-01-01
  • vue3點(diǎn)擊不同的菜單頁切換局部頁面實(shí)現(xiàn)方法

    vue3點(diǎn)擊不同的菜單頁切換局部頁面實(shí)現(xiàn)方法

    這篇文章主要給大家介紹了關(guān)于vue3點(diǎn)擊不同的菜單頁切換局部頁面實(shí)現(xiàn)的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用vue3具有一定的參考價(jià)值,需要的朋友可以參考下
    2023-08-08
  • Vee-validate 父組件獲取子組件表單校驗(yàn)結(jié)果的實(shí)例代碼

    Vee-validate 父組件獲取子組件表單校驗(yàn)結(jié)果的實(shí)例代碼

    vee-validate 是為 Vue.js 量身打造的表單校驗(yàn)框架,允許您校驗(yàn)輸入的內(nèi)容并顯示對(duì)應(yīng)的錯(cuò)誤提示信息。這篇文章主要介紹了Vee-validate 父組件獲取子組件表單校驗(yàn)結(jié)果 ,需要的朋友可以參考下
    2019-05-05

最新評(píng)論

海宁市| 六枝特区| 遵义市| 元阳县| 永新县| 桦南县| 仪陇县| 历史| 垦利县| 安岳县| 临城县| 台前县| 漾濞| 锡林郭勒盟| 溧阳市| 武穴市| 屏山县| 泾阳县| 柘城县| 邵阳县| 全州县| 荆州市| 云安县| 修文县| 河池市| 钟山县| 怀远县| 克什克腾旗| 安义县| 平定县| 昂仁县| 彝良县| 信宜市| 宿州市| 海安县| 泾川县| 内黄县| 长丰县| 廊坊市| 博乐市| 安塞县|