一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

 
<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>
posted on 2021-12-24 14:22  一路繁花似锦绣前程  阅读(159)  评论(0编辑  收藏  举报