在很多项目中,都要进行一些统计,统计的数据要导出到excel中,在某些浏览器中中文名会出现乱码,下面的方法是将数据处理好导出excel,并对文件名处理不乱码。
public function outputExcel($PHPExcel, $filename) { //按照指定格式生成Excel文件,' Excel2007 '表示生成2007版本的 xlsx $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007'); $ua = $_SERVER['HTTP_USER_AGENT']; $ua = strtolower($ua); //判断是否为IE或Edge浏览器 if (preg_match('/msie/', $ua) || preg_match('/edge/', $ua) || preg_match('/trident/', $ua)) { //使用 urlencode 对文件名进行重新 编码 $filename = str_replace('+', '%20', urlencode($filename)); } //2、浏览器保存 ob_end_clean(); header ("Pragma: public"); header(" Expires : 0"); header(" Cache-Control :must-revalidate, post-check=0, pre-check=0"); header("Content-Type:application/force-download"); header("Content-Type:application/octet-stream"); header("Content-Type:application/download"); //告诉浏览器输出07Excel文件 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); //告诉浏览器输出浏览器名称 header('Content-Disposition: attachment;filename=' . $filename . '.xlsx'); header('Cache-Control: max-age=0'); //禁止 缓存 header("Content-Transfer-Encoding:binary"); $PHPWriter->save("php://output"); exit; }