PHP exports data to an Excel table (speculative), and the data is exported to an excel
1. Introduction
How can I write data into an Excel file using the simplest, rough, and violent method?
Because documents in ms word and excel support html text format, we can use html text format to output data based on this principle.
In html, we only need to put the data in the corresponding html table in the desired order.
We use PHP to obtain and sort the data and construct the corresponding html text. Finally, we use byte stream output to download it to the user's local location.
2. Code
Code directly. This is a very simple program with comments in it.
ExportExcel. class. php file
1 <? Php 2 class ExportExcel {3/** 4 * @ desc export data to Excel 5 * @ param $ data array set table data 6 * @ param $ titlename string set head 7 * @ param $ title string: Set the header 8 * @ param $ filename: Set the default file name 9 * @ return to output the string, the output byte stream downloads the Excel file 10 */11 public function excelData ($ data, $ titlename, $ title, $ filename) {12 # xmlns is the xml namespace 13 $ str = "
1 <? Php 2 $ obj = new ExportExcel (); 3 4 $ data = array (5 array ('a11', 'a22', 'a33'), 6 array ('b11 ', 'b22', 'b33'), 7 array ('c11', 'c22', 'c33'), 8 array ('d11', 'd22 ', 'd33'), 9 array ('e11', 'e22', 'e33'), 10 array ('f11', 'f22', 'f33'), 11 ); 12 $ excelHead = "this is the title of an Excel table"; 13 $ title = "My Excel table "; # file name 14 $ headtitle = "<tr> <th colspan = '3' >{$ excelHead} </th> </tr> "; 15 $ titlename = "<tr> 16 <th style = 'width: 70px; '> Table 1 </th > 17 <th style = 'width: 70px; '> Table 2 </th> 18 <th style = 'width: 70px; '> Table 3 </th> 19 </tr> "; 20 $ filename = $ title. ". xls "; 21 $ obj-> excelData ($ data, $ titlename, $ headtitle, $ filename); 22 23 24?>
3. Test
Click to access:
Download the Excel file
View the file after the operation is successful:
After entering, the Excel file prompts that the file format is inconsistent with the extension name. This also indirectly shows that the Excel file we export is only an Excel file (essentially an html file ), the format is not an Excel file.
Click here to view the content. It looks like Excel, haha. Taipa
Change the suffix html to View Details:
You see, the essence is html files, but Excel only supports this format.
4. References
1. PHP Excel Export
(The above are some of your own opinions. If you have any shortcomings or errors, please point them out)
Author: The leaf with the wind http://www.cnblogs.com/phpstudy2015-6/
Address: http://www.cnblogs.com/phpstudy2015-6/p/7260208.html
Disclaimer: This blog post is original and only represents the point of view or conclusion I have summarized at a certain time in my work and study. When reprinting, please provide the original article link clearly on the Article Page