以excel格式导出时,如何在ajax中指定文件名


How to specify the filename in ajax while exporting in excel format

在这段代码中,我想在下载excel格式时指定文件名。

if(comp_id != "Select Company")
{
  $.ajax({
    url: 'includes/export.php',
    data: {
      action: 'compreport', 
      'comp':comp_id,   
    },
    type: 'post',
    success: function (output) {
      $("#ereportview").html(output);
      window.open('data:application/vnd.ms-excel,' + encodeURIComponent( $('div[id$=ereportview]').html()));
      e.preventDefault();
    },
    async: false
  });  
}

success回调中使用此下载功能

function download(filename, text, mime) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:'+mime+',' + encodeURIComponent(text));
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

你可以这样使用它:

if(comp_id != "Select Company") {
  $.ajax({
    url: 'includes/export.php',
    data: {
      action: 'compreport', 
      'comp':comp_id,   
    },
    type: 'post',
    success: function (output) {
      download("yourfile.xlsx", output, 'application/vnd.ms-excel');
    },
    async: false
  });  
}

您可以为正在下载的内容类型指定MIME。您可以从SitePoint 获得