Home >PHP Framework >ThinkPHP >Use thinkphp5 to export excel files
Hello! Some people think that Excel export is complicated, but it is actually very simple. You can export the data you want in two steps, so give it a try.
The first step is to configure excel into the common configuration of the TP framework (Recommended learning: thinkphp5)
// 应用公共文件 /** * 导出excel * @param $strTable 表格内容 * @param $filename 文件名 */ function downloadExcel($strTable, $filename) { header("Content-type: application/vnd.ms-excel"); header("Content-Type: application/force-download"); header("Content-Disposition: attachment; filename=" . $filename . "_" . date('Y-m-d') . ".xls"); header('Expires:0'); header('Pragma:public'); echo '<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . $strTable . '</html>'; }
Second step controller code
You can query the data you want to report and just traverse it in the following td. Simple and convenient, have you learned it?
public function excel_daochu(){ $strTable ='<table width="500" border="1">'; $strTable .= '<tr>'; $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">ID</td>'; $strTable .= '<td style="text-align:center;font-size:12px;" width="*">用户账号</td>'; $strTable .= '<td style="text-align:center;font-size:12px;" width="*">昵称</td>'; $strTable .= '<td style="text-align:center;font-size:12px;" width="*">时间</td>'; $strTable .= '</tr>'; $aa = db("user")->select(); foreach ($aa as $k => &$v) { $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']); } foreach($aa as $k=>$val){ $strTable .= '<tr>'; $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['user_id'].'</td>'; $strTable .= '<td style="text-align:left;font-size:12px; vnd.ms-excel.numberformat:@">'.$val['tel'].'</td>'; $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['ni_name'].' </td>'; $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['add_time'].'</td>'; $strTable .= '</tr>'; } $strTable .='</table>'; downloadExcel($strTable,'用户列表'); exit(); }
The above is the detailed content of Use thinkphp5 to export excel files. For more information, please follow other related articles on the PHP Chinese website!