Simple example of PHP downloading excel files using post of ajax

  • 2021-12-19 06:05:23
  • OfStack

This article illustrates how PHP uses post of ajax to download excel files. Share it for your reference, as follows:

According to the project requirements, the front end initiates ajax request, and the back end generates excel and downloads it. At the same time, it is necessary to bring token verification information in the header header. After referring to many articles, the final implementation is as follows:

PHP backend uses base64:


$filename = 'demo.xlsx';
$objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel2007');
ob_start();
$objWriter->save("php://output");
$xlsData = ob_get_contents();
ob_end_clean();
return Api::success(['filename' => $filename, 'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsData)]);

JS front end:


$('.download').click(function(){
    var url = "http://xxxx.com/group/bi/export";
    var params = {
      from_date: '2017-09-01',
      to_date: '2017-09-08',
      group_id: 1
    };
    $.ajax({
      type:'POST',
      url: url,
      data: params,
      beforeSend: function(request) {
        request.setRequestHeader("Authorization", "token Information, authentication ");
      },
      success: function(redata) {
        //  Create a Tag, set properties, and trigger click download 
        var $a = $("<a>");
        $a.attr("href", redata.data.file);
        $a.attr("download", redata.data.filename);
        $("body").append($a);
        $a[0].click();
        $a.remove();
      }
    });
});

For more information about PHP, please see the topics of this site: "Summary of PHP+ajax Skills and Application", "Summary of php Operating office Document Skills (including word, excel, access, ppt)", "Summary of PHP Network Programming Skills", "Summary of php String Usage (string)", "Introduction Tutorial of php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: