针对PHP程序导出Excel表格时遇到的乱码问题,可以采取以下步骤:
1. 指定文件编码
在使用PHPExcel导出表格时,可以在创建PHPExcel_IOFactory对象时指定编码:
$excel = new \PHPExcel();
$objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
$objWriter->setUseBOM(true); // 设置使用BOM
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="export.xls"');
$objWriter->save('php://output');
上述代码中,setUseBOM的作用是添加BOM头信息,以表明文件编码是UTF-8。BOM头信息可以用windows自带的“写字板”编辑器实现,具体步骤如下:
- 打开写字板,文件->另存为
- 在“文件名”后面的“保存类型”处选择:“所有文件(.)”
- 在文件名后面输入“test.xls”,在“编码”处选择“Unicode”
- 点击“保存”按钮
2. 转换字符编码
如果使用PHPExcel导出表格时未指定编码,那么就需要在程序中进行字符编码转换。如下所示:
$excel = new \PHPExcel();
$worksheet = $excel->getActiveSheet();
$worksheet->setCellValue('A1', '姓名');
$worksheet->setCellValue('B1', '年龄');
$worksheet->setCellValue('C1', '性别');
$worksheet->setCellValue('D1', '国籍');
$worksheet->setCellValue('A2', '张三');
$worksheet->setCellValue('B2', '24');
$worksheet->setCellValue('C2', '男');
$worksheet->setCellValue('D2', '中国');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="export.xls"');
$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
// 将字符编码转换为包含BOM头的GBK
ob_start();
$objWriter->save('php://output');
$data = ob_get_clean();
echo chr(0xEF), chr(0xBB), chr(0xBF), iconv("UTF-8", "GBK//TRANSLIT//IGNORE", $data);
示例说明:
下面是两个示例,分别演示了通过指定文件编码和字符编码转换两种方式解决PHPExcel导出乱码问题。
示例一:
$excel = new \PHPExcel();
$worksheet = $excel->getActiveSheet();
$worksheet->setCellValue('A1', '姓名');
$worksheet->setCellValue('B1', '年龄');
$worksheet->setCellValue('C1', '性别');
$worksheet->setCellValue('D1', '国籍');
$worksheet->setCellValue('A2', '李四');
$worksheet->setCellValue('B2', '26');
$worksheet->setCellValue('C2', '女');
$worksheet->setCellValue('D2', '美国');
$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
// 指定文件编码UTF-8,并添加BOM头信息
$objWriter->setUseBOM(true);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="export.xls"');
$objWriter->save('php://output');
示例二:
$excel = new \PHPExcel();
$worksheet = $excel->getActiveSheet();
$worksheet->setCellValue('A1', '姓名');
$worksheet->setCellValue('B1', '年龄');
$worksheet->setCellValue('C1', '性别');
$worksheet->setCellValue('D1', '国籍');
$worksheet->setCellValue('A2', '王二');
$worksheet->setCellValue('B2', '30');
$worksheet->setCellValue('C2', '男');
$worksheet->setCellValue('D2', '日本');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="export.xls"');
$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
// 将字符编码转换为包含BOM头的GBK
ob_start();
$objWriter->save('php://output');
$data = ob_get_clean();
echo chr(0xEF), chr(0xBB), chr(0xBF), iconv("UTF-8", "GBK//TRANSLIT//IGNORE", $data);
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:完美解决phpexcel导出到xls文件出现乱码的问题 - Python技术站