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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?