在需要导出数据的controller里面增加以下php方法:
/** * 导出 * @throws hinkdbexceptionDataNotFoundException * @throws hinkdbexceptionDbException * @throws hinkdbexceptionModelNotFoundException */ public function export() { $formModel=new FormsModel(); $result=$formModel->scope(['show'])->order($formModel->sort)->select(); $list=$result->toArray(); /* 输入到CSV文件 */ $html = ""; /* 输出表头 */ $filter = array( 'name'=>'姓名', 'mobile' => '手机号', 'content'=>'内容', 'create_time'=>'提交时间', ); foreach ($filter as $key => $title) { $html .= $title . " ,"; } $html .= " "; foreach ($list as $k => $v) { foreach ($filter as $key => $title) { if($key=='form_type'){ $html .= $formModel->form_type[$v[$key]] . " , "; }else{ $html .= $this->replaceValues($v[$key]) . " , "; } } $html .= " "; } /* 输出CSV文件 */ header("Content-type:text/csv"); header("Content-Disposition:attachment; filename=预约表单数据.csv"); echo $html; exit(); } protected function replaceValues($value){ $value = str_replace(" ","",$value);//过滤换行 $value = str_replace(" ","",$value);//过滤换行 $value = str_replace(" ","",$value);//过滤换行 $value = str_replace(" ","",$value);//过滤换行 // $value = str_replace(" ","",$value);//过滤换行 $value = str_replace(",",",",$value);//过滤逗号 return $value; }
以上就是利用Thinkphp导出数据为csv,导出为csv格式的表格就不需要使用第三方的库,使用起来是会相对简单了许多!