美文网首页
JS:数据导出为CSV格式

JS:数据导出为CSV格式

作者: 天山的虫 | 来源:发表于2019-09-29 23:05 被阅读0次

需求

将后台查询出来的Array导出为CSV格式

<!--html-->
...
<button id= "btnExport" onclick = "exportExcel()">导出当前条件添加至CSV</button>
...
<script>
  //不可点击
  $('#btnExport').attr('disable','disabled');
  //后台返回的数据
  var array= [];
  //从后台获取数据
  $.ajax({
      url: /../../..,
      data:{ keyword:keyword,pageIndex:pageIndex,pageSize:20},
      type:"GET",
      async:false,
      success:function (response){
                   if(!response.code || response.code == 0){
                              alert(response.message);
                   }
                   array = response.data;
      },
      error:function(response){
                  //to do somethings
      }
   //点击下载
   var str = "字段A,字段B,字段C,字段D  \n";
   for(var i= 0;i<array.length,i++){
             for(var item in array[i]){
                 str += array[i][item] + '\t' +',';
             }
   }
  });
  if(array.length == 0){
      alert("查询条件没有数据!");
      return ;
  }
  var url = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
  var link = document.createElement("a");
  link.href = url;
  link.download = "data.csv";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  $('#btnExport').removeAttr('disabled');
</script>

参考:

JS导出数据为表格

相关文章

网友评论

      本文标题:JS:数据导出为CSV格式

      本文链接:https://www.haomeiwen.com/subject/xoppuctx.html