开发者

dumping data from database to excel file using php 4.3.9

开发者 https://www.devze.com 2023-02-21 15:03 出处:网络
I am recently using the following code to export my data in database as an excel file. But the output is showing as html page with correct data from database.

I am recently using the following code to export my data in database as an excel file. But the output is showing as html page with correct data from database.

<?php
/* database connection here */

$file_type = "vnd.ms-excel";
$file_ending = "xls";
header("Content-Type: application/$file_type");
header("Content-Disposition: attachment; filename=$tabl开发者_Go百科e.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");

/* extract from database */

It pulls out the all data from database so I assume database function are correct but its just not saving as excel file. This code I used exactly the same in my previous project and working fine. Any idea how to solve this? plz help.


My advice is to inspect the generated HTTP headers and make sure they are correct. You can use Firebug's "Net" panel or the tool of your choice.

In any case, this part of your description suggests that you are not generating an Excel file:

the output is showing as html page with correct data from database

Excel files are binary files. If shown in the browser, they'll look like garbage. I suspect you are telling the browser "Here you are an Excel spreadsheet" and then sending HTML.


BTW, the Expires header does not look correct. It should contain a string with a date rather than an integer:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21

As the spec says, the browser must handle the 0 as in the past but it isn't a correctly value anyway.


Finally just found out this is the same problem I had. Just solved it by just setting UTF-8 to UTF-8 without BOM in my editor.... code was seems correct but here is better header content I am using now. Thank you guys for help. ;)

        header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Disposition: attachment;filename=".$filename.".xls");
    header("Content-Transfer-Encoding: binary ");


You can use this class which lets you create excel files from PHP

PHP Class for Reading/Writing Excel Files

Another one

I recommend the first one though.


There's a list of PHP libraries for reading/writing Excel files in the response to this question. I'm not sure how many of them will work with PHP4 (certainly most require PHP5), but you might find something here that will.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号