手记

用php把数据导出excel

一:先获取数据

<!--more-->

public function output($dataResult=array()){
    $headTitle = date('YmdHis');
    $title = date('YmdHis');
    $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 = '';
    $headtitle = "<tr>
           <th>ID</th>
           <th>条码号</th>
           <th>商品组合</th>
           <th>项目明细</th>
           <th>病人</th>
           <th>医生姓名</th>
           <th>医生折扣</th>
           <th>代理姓名</th>
           <th>业务员</th>
           <th>原价</th>
           <th>实付</th>
           <th>退款</th>
           <th>日期</th>
       </tr>";
    $filename = $title.".xls";
    $this->excelData($dataResult,$titlename,$headtitle,$filename);
}

二:输出

    /*
 *处理Excel导出
 *@param $datas array 设置表格数据
 *@param $titlename string 设置head
 *@param $title string 设置表头
 */
private 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");
    //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 );
}
5人推荐
随时随地看视频
慕课网APP