vue、element、axios、api 实现下载 excel 文件


本篇文章记录如何结合:axios请求后台实现下载excel文件前端

 

 前端页面+脚本vue

1 <el-form-item>2  <el-button type="primary" icon="el-icon-search" v-on:click="getList">查询</el-button>3 </el-form-item>4 <el-form-item>5  <el-button type="primary" icon="el-icon-download" :loading="onDownLoading" v-on:click="DownLoad">下载</el-button>6 </el-form-item>

vue实现:ios

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

1 var vm = new Vue({ 2  el: '#vm_table', 3  data() { 4   return { 5    onDownLoading: false, //下载中动画 6   } 7  }, 8  methods: {  9 10   //下载11   async DownLoad() {12    vm.onDownLoading = true; //显示下载中动态图13    var param = vm.filter; //参数14 15    //异步下载16    axios.request({17     method: 'post',18     baseURL: this.apiUrl,19     url: '/xxxx/xxxx',20     params: param,21     responseType: 'blob', //接收类型22    }).then(function (res) {23     vm.onDownLoading = false; //关闭下载中动态图24     if (res.status == 200) {25      let fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]; //excel文件名称26      let blob = new Blob([res.data])27      if (window.navigator.msSaveOrOpenBlob) {28       navigator.msSaveBlob(blob, fileName);29      } else {30       //非IE下载31       var link = document.createElement('a');32       link.href = window.URL.createObjectURL(blob);33       link.download = fileName;34       link.click();35       window.URL.revokeObjectURL(link.href); //释放url对象36      }37     } else {38      vm.$message.error('下载失败,请刷新后从新尝试');39     }40    }).catch(function (res) {41     vm.onDownLoading = false; //关闭下载中动态图42     vm.$message.error('请求异常,刷新后从新尝试');43    })44   },45 46  }47 });

View Code数据库

服务端实现:axios

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

1 //下载excel文件 2 [HttpPost] 3 public FileResult DownLoad() 4 { 5  var loginname = Request["loginName"].AsStringWhiteSpace(); 6  var mobile = Request["Mobile"].AsStringWhiteSpace(); 7  try 8  { 9   //查询数据库,返回一个DataTable10   DataTable datatabla = RecordsBll.DownLoadRecords(loginname,mobile);11   if (datatabla != null)12   {13    //文件名14    var fileName = DateTime.Now.Ticks.ToString() + ".xlsx";15    if (datatabla.Rows.Count > 50000)16    {17     fileName = DateTime.Now.Ticks.ToString() + ".csv";18    }19    var getbuffer = ExcelHelper.ExportDataTableToExcel(datatabla, true);20    return File(getbuffer, "application/ms-excel".........