PHP export Excel

Article source blogger: https://www.cnblogs.com/followyou/p/6143168.html

/* 
* Process Excel export
*@param $datas array set table data
*@param $titlename string set head
*@param $title string set header
*/ 
public function excelData($datas,$titlename,$title,$filename){ 
    $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>"; 
    $str .="<table border=1><head>".$titlename."</head>"; 
    $str .= $title; 
    foreach ($datas  as $key=> $rt)
    {
        $str .= "<tr>"; 
        foreach ( $rt as $k => $v ) 
        {
            $str .= "<td>{$v}</td>"; 
        }
        $str .= "</tr>\n"; 
    }
    $str .= "</table></body></html>"; 
    header( "Content-Type: application/vnd.ms-excel; name='excel'" ); 
    header( "Content-type: application/octet-stream" ); 
    header( "Content-Disposition: attachment; filename=".$filename ); 
    header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" ); 
    header( "Pragma: no-cache" ); 
    header( "Expires: 0" ); 
    exit( $str ); 
}

Convert the html table to the excel table; this method is suitable for setting the display and merging of various cells, only need to set the html table, and set the css to export various excel templates.

The example is as follows:
export a header with a color, set the font size, center, and moderate typesetting;

$dataResult = array ();       // todo: export data (set by yourself) 
$headTitle = "XX insurance company coupon gift record" ; 
 $title = "coupon record" ; 
 $headtitle = "<tr style='height: 50px;border-style:none;><th border=\"0\" style='height:60px;width:270px;font-size:22px;' colspan='11' >{ $headTitle }</th> </tr>" ; 
 $titlename = " <tr>
               <th style='width:70px;' >Partners</th>
               <th style='width:70px;' >membership card number</th>
               <th style='width:70px;'>owner's name</th>
               <th style='width:150px;'>Mobile number</th>
               <th style='width:70px;'>License plate number</th>
               <th style='width:100px;'>Coupon type</th>
               <th style='width:70px;'>Coupon name</th>
               <th style='width:70px;'>Coupon face value</th>
               <th style='width:70px;'>Number of coupons</th>
               <th style='width:70px;'>Gift time</th>
               <th style='width:90px;'>until the validity period</th>
           </tr>"; 
           $filename = $title.".xls"; 
       $this->excelData($dataResult,$titlename,$headtitle,$filename); 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324888722&siteId=291194637