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 ;)

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

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)