Exporting excel table with php header function

Keywords: PHP Excel Database

In addition to exporting tables with PHPExcel, another simple table import method that does not need to import class files is recommended: header() exports excel tables.

The steps of exporting the table are encapsulated into a method for reuse. The code is as follows:

 1 /**
 2  * Export data to excel
 3  *@param $data    A two-dimensional array, the structure of which is similar to the array found from the database
 4  *@param $title   excel The first row title of, an array, if empty, no title
 5  *@param $filename Downloaded file name
 6  *@examlpe10  */
11 function exportexcel($data=array(),$title=array(),$filename='report'){
12     ob_end_clean(); 
13     ob_start(); 
14     header("Content-type:application/octet-stream");
15     header("Accept-Ranges:bytes");
16     header("Content-type:application/vnd.ms-excel");
17     header("Content-Disposition:attachment;filename=".$filename.".xls");
18     header("Pragma: no-cache");
19     header("Expires: 0");
20     //export xls start
21     if (!empty($title)){
22         foreach ($title as $k => $v) {
23             $title[$k]=iconv("UTF-8", "GB2312",$v);
24         }
25         $title= implode("\t", $title);
26         echo "$title\n";
27     }
28     if (!empty($data)){
29         foreach($data as $key=>$val){
30             foreach ($val as $ck => $cv) {
31                 $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
32             }
33             $data[$key]=implode("\t", $data[$key]);
34         }
35         echo implode("\n",$data);
36     }
37 }

A simple example

1 $data =M ('User')-> select();
2 $title = array('id','account','Password','Nickname?');
3 exportexcel($data,$title,'User table!');

The ob_end_clean() and ob_start() functions in the method are mainly used to clear the cache and the boom header to prevent garbled code and format errors. If you need to do the export operation, define a two-dimensional array, and a header header array, and then directly call download.

This is the original content. In order to respect the work of others, please indicate the address of this article:

http://www.cnblogs.com/luokakale/p/8352517.html

Posted by Valera on Mon, 04 May 2020 23:51:50 -0700