js编辑excel并下载

<template>
  <div id="app">
    <button @click="writeExcel">按钮</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
    return {
      table:[
        {
          name: 'C罗',
          country: '葡萄牙',
          pic: 'https://dss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=3375134598,1577355399&fm=58'
        },
        {
          name: '梅西',
          country: '阿根廷',
          pic: 'https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=100059772,95063167&fm=111&gp=0.jpg'
        },
        {
          name: '内马尔',
          country: '巴西',
          pic: 'https://dss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=2186912775,1920732168&fm=58'
        },
        {
          name: '伊布',
          country: '瑞典',
          pic: 'https://dss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=3518710826,1372793792&fm=58'
        }
      ]
    }
  },
  methods:{
    writeExcel(){
      let excelML=this.json2excelML()
      let bs64=this.excelML2base64(excelML)
      this.downloadBase64(bs64)
    },
    json2excelML(){
      let trs=""
      this.table.forEach(li=>{
        let tds=""
        for(let key in li){
          if (/http/.test(li[key])) { // 处理图片数据
            tds+=`<td style="width: 180px;height: 200px;"><img src="${li[key]}" width="180" height="200"></td>`
          } else {
            tds+=`<td>${li[key]}</td>`
          }
        }
        trs+=`<tr>${tds}</tr>`
      })

      return `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
              <head>
                <meta charset="UTF-8">
                <!--[if gte mso 9]>
                <xml>
                  <x:ExcelWorkbook>
                    <x:ExcelWorksheets>
                      <x:ExcelWorksheet>
                        <x:Name>Sheet1</x:Name>
                        <x:WorksheetOptions>
                          <x:DisplayGridlines/>
                        </x:WorksheetOptions>
                      </x:ExcelWorksheet>
                    </x:ExcelWorksheets>
                  </x:ExcelWorkbook>
                </xml>
                <![endif]-->
              </head>
              <body>
                <table>
                  <tbody>${trs}</tbody>
                </table>
              </body>
              </html>`
    },
    excelML2base64(excelML){
      return 'data:application/vnd.ms-excel;base64,'+window.btoa(unescape(encodeURIComponent(excelML)))
    },
    downloadBase64(bs64){
      let link = document.createElement('a');
      link.setAttribute('href', bs64);
      link.setAttribute('download', new Date().getTime());
      link.click();
    }
  }
}
</script>

<style scoped>
</style>
上一篇:python 字典取(不存在)值


下一篇:(39)css3实现轮播图效果