前端导出excel,并且设置单元格为文本格式

前端导出excel可以通过如下方式

  tableToExcel(str: string, fileName: string) {
    const worksheet = 'Sheet1'
    const uri = 'data:application/vnd.ms-excel;base64,'
    const template = `<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><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        <style type="text/css">  
        .bg-gray {
          background: #aaa;
          }
          .bg-gray td {
             text-align: left;
          }
          th,td {
            text-align: center;
            mso-number-format:\@;
            vnd.ms-excel.numberformat:\@;
          }
          
        </style>
        </head><body><table>${str}</table></body></html>`
    const a = document.createElement('a')
    a.download = fileName + '.xls'
    a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
    a.click()
  }

在我们导出excel时,默认单元格格式为常规,这个时候如果我们单元格中存在0123,或者10.00或者9.0时候,导出后的excel中单元格格式为123,10,9,没能按照原样导出,找了很多文章,网上解决办法是通过给td添加style="mso-number-format:\@;"  这种方式可能对于在微软excel打开没有问题(具体我没有去看),但是我配置完后,发现仍然不生效(可能因为我使用的是wps),通过不断尝试:最终解决方案:

          
th,td {
            text-align: center;
            mso-number-format:\@;
            vnd.ms-excel.numberformat:\@;
          }

添加vnd.ms-excel.numberformat:\@;mso-number-format:\@;添加两种方式。亲测导出数据正常。

  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值