1. Introduction
How can you use the simplest rough brute force method to write data to an Excel file?
Because both MS Word and Excel documents support HTML text formatting, we can use HTML text format for data output based on this principle.
In HTML, we just need to put the data in the desired order into the appropriate HTML table.
We use PHP to get the data sorted and construct the corresponding HTML text, and finally download the output to the user locally via the byte stream.
2. Code
Directly on the code, this is a very simple program, there are comments.
ExportExcel.class.php file
<?phpclass exportexcel{/** * @desc Export data to Excel * @param $data array to set tabular data * @param $titlename Strin G Set head * @param $title String Set header * @param $filename Set Default file name * @return string output, Output byte stream, download Excel file */P ublic function Exceldata ($data, $titlename, $title, $filename) {#xmlns即是xml的命名空间 $str = "
<?php$obj=new Exportexcel (); $data = Array ( ' A11 ', ' A22 ', ' A33 '), array (' B11 ', ' B22 ', ' b33 '), Array (' C11 ', ' C22 ', ' C33 '), array (' D11 ', ' d22 ', ' d33 '), array (' E11 ', ' E22 ', ' e33 '), Array (' F11 ', ' f22 ', ' F33 '), ); $excelHead = "This is the Excel table title"; $title = "My Excel table"; #文件命名 $headtitle = "<tr><th colspan= ' 3 ' >{$excelHead}</th></tr>"; $titlename = "<tr > <th style= ' width:70px; ' > Form 1</th> <th style= ' width:70px; ' > Form 2</th> <th style= ' width:70px; ' > Form 3</th> </tr> "; $filename = $title.". XLS "; $obj->exceldata ($data, $titlename, $headtitle, $filename);?>
3. Testing
Click to visit:
Download the Excel file
After successful viewing the file:
After entering the Excel prompt said that the file format is inconsistent with the suffix name, which also indirectly indicates that the Excel file we have introduced is only a physical appearance is Excel (essentially HTML file), the format is not an Excel file.
Click is to enter the contents of the view inside, look like Excel, haha. Just Jiangzi.
Change the suffix named HTML into view:
You see, the real thing is the HTML file, but Excel supports that format.
4. Reference documents
"PHP Export Excel"
(These are some of their own ideas, if there is insufficient or wrong place please point out)