Output Excel file in PHP after echo

自作多情 提交于 2020-01-30 03:17:26

问题


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?


回答1:


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...




回答2:


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




回答3:


This has been discussed before at StackOverflow:

Export MYSQL result to Excel..

PHP code to convert a MySQL query to CSV

See also these examples and tutorials:

Easy way to create XLS file from PHP

Export MYSQL data to CSV – PHP tutorial

PHP Script: Export MYSQL Table Data to CSV

Advanced CSV Export




回答4:


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



回答5:


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.



来源:https://stackoverflow.com/questions/1629945/output-excel-file-in-php-after-echo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!