htmlTableToExcel

    //导出excel
    public function dataToExcel($filename, $data, $header, $keys)
    {
        $html = $this->dataToHtml($data, $header, $keys);
        return $this->htmlToExcel($filename, $html);
    }

    public function dataToHtml($data, $header, $keys)
    {
        $str = "<html><head><meta charset=\"utf-8\"></head><body>";
        $str .= "<table border=\"1\"><tr>";
        foreach ($header as $v) {
            $str .= "<th>{$v}</th>";
        }
        $str .= "</tr>";
        foreach ($data as $row) {
            $str .= "<tr>";
            foreach ($keys as $v) {
                $str .= "<td>{$row[$v]}</td>";
            }
            $str .= "</tr>";
        }
        $str .= "</table><body></html>";
        return $str;
    }

    public function htmlToExcel($filename, $html)
    {
        header("Content-Type: application/vnd.ms-excel;charset=utf-8; name='excel'");
        // header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        // header( "Content-type: application/octet-stream" );
        header("Content-Disposition: attachment; filename=" . $filename . '.xls');
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        header("Expires: 0");
        exit($html);
    }

 

posted @ 2021-09-07 08:45  CanyingV  阅读(85)  评论(0编辑  收藏  举报