Output Excel file in PHP after echo

2019-02-20 12:05发布

HI,

I am trying to display results from a database in results.php. In the same file, after all the data has been displayed in the current webpage,I am placing a button to create a file based on this results to produce a Excel file.

I am not sure how to do this. I have tried but it says you have to force excel file download before any echo, but I want to display as well as produce an excel file. Is this possible or am I missing something? can anyone please let me know how to do this correctly?

5条回答
啃猪蹄的小仙女
3楼-- · 2019-02-20 12:42

You could create a .cvs-file which are a lot simpler than xls-files, and the best part is that excel supports .cvs-files.

Then while you are outputting your data to the user, have a seperate variable called something like $cvs which you apply the same data as you output, just in the .cvs-format and when you're done you write $cvs to a file.

Then you just link to that file at the bottom of the page.

You may have to force the download upon the user though.

查看更多
放荡不羁爱自由
4楼-- · 2019-02-20 12:44

You have to change the header for the page, so you have to open the output for the excel file in a new window.

Header type: "application/vnd.ms-excel" .

If you want to create "good" Excel sheets , take a look on PHPExcel

PHPExcel

查看更多
男人必须洒脱
5楼-- · 2019-02-20 12:44

Set your headers first and then echo your CSV output:

header("Content-type: application/text/x-csv");
header("Content-disposition: attachment; filename=report.csv");
echo "value1,value2\n";
echo "value3,value4\n";
查看更多
ら.Afraid
6楼-- · 2019-02-20 12:48

You're probably faceing an 'Header allready set' error. You need to separe the two steps in order to make that work. One step for displaying and one for excel file creation and downloading.

On th other hand you could combine the data display and excel creation too and eventually display a download link.

Just pokin in the dark, let us know which way you wanna go and we'll be helping you along...

查看更多
登录 后发表回答