最近一直在折腾PHP,无意间想实现个导出表格的功能。
不料用了header声明后的表格中文是乱码的,后来通过转字符、添加字母符号、style等方法才得以让excel导出后显示正常了。
为了解决部分MySQL环境设置问题,又添加了一个CSV的导出方法。
导出Excel代码
header("Content-type:application/vnd.ms-excel;charset=UTF-8"); header("Content-Disposition:attachment;filename=xxxxx.xls"); //输出标题 echo "<table border='1'>"; echo "<th>".mb_convert_encoding($str, "GBK","UTF-8")."</th>"; echo "<th>".mb_convert_encoding($str, "GBK","UTF-8")."</th>"; echo "<th>".mb_convert_encoding($str, "GBK","UTF-8")."</th>"; #.... //输出每行的内容 for ($i=0; $i < count($Data); $i++) { echo "<tr>"; for ($n=0; $n < count($Data[$i]); $n++) { //添加 style='vnd.ms-excel.numberformat:@' 将内容作为字符串识别 echo "<td style='vnd.ms-excel.numberformat:@'>"; echo mb_convert_encoding($Data[$i][$n],"GBK","UTF-8"); echo "</td>"; } echo "</tr>"; } echo "</table>";
导出CSV代码
封装好的函数,会对数字等内容进行判断,并添加英文符号,以防止excel转格式。
/** * 导出CSV文件 * @param string $fileName 文件名字 * @param string|array $data 导出数据,csv格式的字符串|数值数组 * @param string $to_encoding 目标转换编码 * @param string $from_encoding 当前编码 */ function exportCSV($fileName = '', $data = '', $to_encoding = 'gb2312', $from_encoding = 'utf-8') { $fileName = empty($fileName) ? date('YmdHis') : $fileName; // 文件标签 Header("Content-type: application/octet-stream"); header("Content-type: application/vnd.ms-excel; charset=$from_encoding"); Header("Content-Disposition: attachment; filename=$fileName.csv"); $str = ''; if($data) { if(is_array($data)) { foreach ($data as $v) { if(is_array($v)) { foreach ($v as $vo) { $str .= (is_numeric($vo) ? "'".$vo : $vo."").","; } $str = trim($str, ",")."\r\n"; } else { $str .= (is_numeric($v) ? "'".$v : $v).","; } } $str = trim($str, ",")."\r\n"; } else { $str = $data; } } echo mb_convert_encoding($str, "gb2312", "utf-8"); exit; } exportCSV($fileName=$str,$data = $Data); ?>