drmqzb5063 2014-05-29 01:28
浏览 43
已采纳

通过php问题将数据导出到.xls

I am exporting data to a .xls file through php and having the following issue: when I export few rows, it's working ok, but when I export a large amount of rows, the spreadsheet is downloaded as a .php file.

A summary of my code (named export.php):

header("Content-type: application/vnd.ms-excel;");

echo 'Column1' . "\t" . 'Column2' . "\t" . 'Column3' . "
";

while($data = $sql_data->fetch(PDO::FETCH_ASSOC)){
   echo $data['column1'] . "\t" . $data['column2'] . "\t" . $data['column3'] . "
";
}

header("Content-disposition: attachment; filename=file.xls");

When the exported spreadsheet is very large, it comes with the filename and extension of the php script (export.php) and yet I can open it with Microsoft Excel. So, I only wish it to come with the right filename and extension (file.xls) regardless of file size.

Any idea?

  • 写回答

1条回答 默认 最新

  • dongyi1982 2014-05-29 01:33
    关注

    You should put your header calls at the top. If your code accidentally outputs anything, all your headers will get flushed. And that's why it's downloading as php. The header call that defines the "file.xls" filename and download-as-attachment behavior is below the while loop.

    Header calls need to come before any data is output to the screen.

    You can read more about php's Output Controls here.

    header("Content-type: application/vnd.ms-excel;");
    header("Content-disposition: attachment; filename=file.xls");
    
    echo 'Column1' . "\t" . 'Column2' . "\t" . 'Column3' . "
    ";
    while($data = $sql_data->fetch(PDO::FETCH_ASSOC)){
       echo $data['column1'] . "\t" . $data['column2'] . "\t" . $data['column3'] . "
    ";
    }
    

    As far as why your code does this on large files, is probably because you're exceeding your maximum buffer size, and it just dumps whatever it has until that point. Either increase your memory limits in PHP, or create smaller spreadsheets ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动