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?
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
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...
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
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";
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.
精彩评论