Php tutorial to generate excel xls document
Method 1-use the HTTP Header
As described in MS Word, You Need To Format HTML/PHP pages using Excel-friendly CSS and header information
Add to your PHP script.
<? Php
Header ("Content-type: application/vnd. ms-excel ");
Header ("Content-Disposition: attachment?filename=document_name.xls ");
Echo "Echo "<meta http-equiv =" Content-Type "content =" text/html;
Charset = Windows-1252 "> ";
Echo "<body> ";
Echo "<B> testdata1 </B> t <u> testdata2 </u> t n ";
Echo "</body> ";
Echo "?>
Method 2-Use a COM Object
Note that the code described in MS Excel must be installed after running on the server.
We use a file to save to the temporary directory first, as the same practice of MS Word.
// Create new COM object-excel. application
$ Xl = new COM ("excel. application ");
// Hide MS Excel application window
$ Xl-> Visible = 0;
// Create new document
$ XlBook = $ xl-> Workbooks-> Add ();
// Create Sheet 1
$ XlBook-> Worksheets (1)-> Name = "Worksheet 1 ";
$ XlBook-> Worksheets (1)-> Select;
// Set Width & Height
$ Xl-> ActiveSheet-> Range ("A1: A1")-> ColumnWidth = 10.0;
$ Xl-> ActiveSheet-> Range ("B1: B1")-> ColumnWidth = 13.0;
// Add text
$ Xl-> ActiveSheet-> Cells (1, 1)-> Value = "TEXT ";
$ Xl-> ActiveSheet-> Cells (1, 1)-> Font-> Bold = True;
// Save document
$ Filename = tempnam (sys_get_temp_dir (), "excel ");
$ XlBook-> SaveAs ($ filename );
// Close and quit
Unset ($ xlBook );
$ Xl-> ActiveWorkBook-> Close ();
$ Xl-> Quit ();
Unset ($ xl );
Header ("Content-type: application/vnd. ms-excel ");
Header ("Content-Disposition: attachment?filename=document_name.xls ");
// Send file to browser
Readfile ($ filename );
Unlink ($ filename );