search
HomeBackend DevelopmentPHP Tutorialphp excel 导出乱码问题

php excel 导出乱码问题

May 26, 2018 am 11:12 AM
excelphpGarbled charactersExport


/**     
* 用于生成excel文件的函数     
* author:walker     
* @param $data 生成excel的数据(二维数组形式)     
* @param null $savefile 生成excel的文件名(保不指定,则为当前时间戳)     
* @param null $title 生成excel的表头(一维数组形式)     
* @param string $sheetname 生成excel的sheet名称(缺省为sheet1)     
*/    
function exportExcel($data,$savefile=null,$title=null,$sheetname='sheet1'){        
//若没有指定文件名则为当前时间戳        
if(is_null($savefile)){            
$savefile=time();        
}        
//若指字了excel表头,则把表单追加到正文内容前面去        
if(is_array($title)){            
array_unshift($data,$title);        
}        import('Org.Util.PHPExcel');		
import('Org.Util.PHPExcel.IOFactory');        
import('PHPExcel.Util.PHPExcel.Reader.Excel5');        
$objPHPExcel = new \PHPExcel();        
//Excel内容        
foreach($data as $k => $v){            
$obj=$objPHPExcel->setActiveSheetIndex(0);            
$row=$k+1;//行            
$nn=0;            
foreach($v as $vv){                
$col=chr(65+$nn);//列                
$vv = iconv("UTF-8", "GB2312//IGNORE",$vv);                
$obj->setCellValue($col.$row,$vv);//列,行,值                
$nn++;            
}        
}        
$objPHPExcel->getActiveSheet()->setTitle($sheetname);        
$objPHPExcel->setActiveSheetIndex(0);        
header('Content-Type: application/vnd.ms-excel');        
header('Content-Disposition: attachment;filename="'.$savefile.'.xls"');        
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");        
header('Cache-Control: max-age=0');        
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');        
$objWriter->save('php://output');        
exit;    }     
/**     
*     
* 导出Excel     
*/    
function expUser(){//导出Excel        
$xlstitle  = array('id','商品编码','模板编号','商品名称','总库存','当前库存','供应商');        
$xlssql = M('erp_inventory');        
$xlsData  = $xlssql->getField('id,p_code,mid,pname,banlance,cur_banlance,factory');
//         show_bug($xlsData);die;       
$this->exportExcel($xlsData,time(),$xlstitle);             
}

以上是我代码,我用thinkphp框架,第二张图是导出后的效果,哪里出现的问题,怎么解决?

回复讨论(解决方案)

注释掉29行 $vv = iconv("UTF-8", "GB2312//IGNORE",$vv);

注释掉29行 $vv = iconv("UTF-8", "GB2312//IGNORE",$vv);


一开始就没有29行的,我后来加的,加不加 导出来的效果一样哦!!

既然用的是 thinkphp,那么就应该是 utf-8 的了  
而 PHPExcel 的默认字符集也是 utf-8 的  
那么为什么要   
$vv = iconv("UTF-8", "GB2312//IGNORE",$vv);  
将 utf-8 转成 gb2312 呢?  

贴出52行,$xlsData打印出来的部分代码,是个二维数组,这里应该没有问题的。希望能给大神一点帮助

$vv = iconv("UTF-8", "GB2312//IGNORE",$vv);  
$vv = iconv("UTF-8", "UTF-8//IGNORE",$vv);  
$vv = iconv("GB2312", "UTF-8//IGNORE",$vv);  
以上3种都试了,结果一样啊!!  

既然用的是 thinkphp,那么就应该是 utf-8 的了  
而 PHPExcel 的默认字符集也是 utf-8 的  
那么为什么要   
$vv = iconv("UTF-8", "GB2312//IGNORE",$vv);  
将 utf-8 转成 gb2312 呢?

看不懂?我没说清楚吗?看来你不能接受启发式解答  
把所有使用 iconv 转码的语句删去!  
这应该明白了吧?  
用 PHPExcel 写到 excel 的必须是 utf-8 编码的数据  
这也应该明白了吧?  

转为gbk看下,另iconv转火星文和繁体字会有问题  
$vv = mb_convert_encoding($vv =, "GBK","UTF-8");

看不懂?我没说清楚吗?看来你不能接受启发式解答  
把所有使用 iconv 转码的语句删去!  
这应该明白了吧?  
用 PHPExcel 写到 excel 的必须是 utf-8 编码的数据  
这也应该明白了吧?

了解,29,38行 删了 还是没用呀,还要删哪里?

转为gbk看下,另iconv转火星文和繁体字会有问题  
$vv = mb_convert_encoding($vv =, "GBK","UTF-8");

$vv =,  什么意思?

38不需要删  
 
还不行的话,就贴个截图

转为gbk看下,另iconv转火星文和繁体字会有问题    
$vv = mb_convert_encoding($vv =, "GBK","UTF-8");

$vv =,  什么意思?
笔误,$vv

转为gbk看下,另iconv转火星文和繁体字会有问题    
$vv = mb_convert_encoding($vv =, "GBK","UTF-8");

$vv =,  什么意思?
笔误,$vv
过不了呢、

38不需要删  
还不行的话,就贴个截图

38行补上了,难道是因为WPS的原因?公司用的WPS,家里用的office2007,不过目前是乱码了。怎么破

方法一:  
setlocale(LC_ALL, 'zh_CN');  
方法二:  
$str = mb_convert_encoding($str, "UTF-8", "GBK"); //已知源码为GBK,转换为utf-8   
可以参见博客。虽然我导的是csv文件,但是我想道理应该是一样的。  
http://blog.csdn.net/phpfenghuo/article/details/17483261

方法一:  
setlocale(LC_ALL, 'zh_CN');  
方法二:  
$str = mb_convert_encoding($str, "UTF-8", "GBK"); //已知源码为GBK,转换为utf-8   
可以参见博客。虽然我导的是csv文件,但是我想道理应该是一样的。  

方法一:LC_ALL 是什么东西  
方法二:报错  
这两句都放在那里啊?我放在28行后,代替$vv 不行呢、

不是很清楚 Untitled Spreadsheet、Unknown Creator 是如何来的  
为什么是 $obj=$objPHPExcel->setActiveSheetIndex(0);  
而不是 $obj = $objPHPExcel->getActiveSheet();

刚才单独测试了一下,你的首发代码应该是没有问题的,当然是没有 iconv 的  
问题在于文档中出现的 Untitled Spreadsheet、Unknown Creator 是如何产生的  

不是很清楚 Untitled Spreadsheet、Unknown Creator 是如何来的  
为什么是 $obj=$objPHPExcel->setActiveSheetIndex(0);  
而不是 $obj = $objPHPExcel->getActiveSheet();

按照你说的,变成这样了,Untitled Spreadsheet、Unknown Creator没有了

转为gbk看下,另iconv转火星文和繁体字会有问题      
$vv = mb_convert_encoding($vv =, "GBK","UTF-8");

$vv =,  什么意思?
笔误,$vv
过不了呢、
extension=php_mbstring.dll把这个扩展开了

转为gbk看下,另iconv转火星文和繁体字会有问题      
$vv = mb_convert_encoding($vv =, "GBK","UTF-8");

$vv =,  什么意思?
笔误,$vv       
过不了呢、
extension=php_mbstring.dll把这个扩展开了
php 的extension=php_mbstring.dll 开启了,重启apache,导出没有报错,但还是乱码  

你没注意还是有错误信息吗?  
A4的Worksheet...Feuilles de calcul  
原来的  
        $objPHPExcel->getActiveSheet()->setTitle($sheetname);  
        $objPHPExcel->setActiveSheetIndex(0);  
并没有错!

不是很清楚 Untitled Spreadsheet、Unknown Creator 是如何来的    
为什么是 $obj=$objPHPExcel->setActiveSheetIndex(0);    
而不是 $obj = $objPHPExcel->getActiveSheet();     

按照你说的,变成这样了,Untitled Spreadsheet、Unknown Creator没有了   
刚看错了,应该是28行,还是乱码。

你没注意还是有错误信息吗?  
A4的Worksheet...Feuilles de calcul  
原来的  
        $objPHPExcel->getActiveSheet()->setTitle($sheetname);  
        $objPHPExcel->setActiveSheetIndex(0);  
并没有错!


那代码又回来刚开始了,那个乱码的excel 我可以在excel设置里面改编码吗?

对,有转回去了  
 
我前面说了,我单独测试你的代码段是没有问题的。  
所以问题可能出在别的地方:比如传入的数据、从表中读取的数据、甚至是你使用的phpexcel类  
 

include 'Plugin/PHPExcel/Classes/PHPExcel.php';
//        import('Org.Util.PHPExcel.IOFactory');
//        import('PHPExcel.Util.PHPExcel.Reader.Excel5');
$data = array(  array('中','文','c'),  array('a','b','c'),  array('a','b','c'),);
$sheetname = '123';
$savefile = time();        
$objPHPExcel = new PHPExcel();        
//Excel内容        
foreach($data as $k => $v){            
$obj=$objPHPExcel->setActiveSheetIndex(0);            
$row=$k+1;//行            
$nn=0;            
foreach($v as $vv){                
$col=chr(65+$nn);//列$vv = iconv('gbk', 'utf-8', $vv);                
$obj->setCellValue($col.$row,$vv);//列,行,值                
$nn++;            
}        
}        
$objPHPExcel->getActiveSheet()->setTitle($sheetname);        
$objPHPExcel->setActiveSheetIndex(0);        
header('Content-Type: application/vnd.ms-excel');        
header('Content-Disposition: attachment;filename="'.$savefile.'.xls"');        
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");        
header('Cache-Control: max-age=0');        
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');        
$objWriter->save('php://output');

对,有转回去了  
 
我前面说了,我单独测试你的代码段是没有问题的。  
所以问题可能出在别的地方:比如传入的数据、从表中读取的数据、甚至是你使用的phpexcel类  

include 'Plugin/PHPExcel/Classes/PHPExcel.php';
//        import('Org.Util.PHPExcel.IOFactory');
//        import('PHPExcel.Util.PHPExcel.Reader.Excel5');
$data = array(  array('中','文','c'),  array('a','b','c'),  array('a','b','c'),);
$sheetname = '123';
$savefile = time();        
$objPHPExcel = new PHPExcel();        
//Excel内容        
foreach($data as $k => $v){            
$obj=$objPHPExcel->setActiveSheetIndex(0);            
$row=$k+1;//行            
$nn=0;            
foreach($v as $vv){                
$col=chr(65+$nn);//列
$vv = iconv('gbk', 'utf-8', $vv);                
$obj->setCellValue($col.$row,$vv);//列,行,值                
$nn++;            
}        
}        
$objPHPExcel->getActiveSheet()->setTitle($sheetname);        
$objPHPExcel->setActiveSheetIndex(0);        
header('Content-Type: application/vnd.ms-excel');        
header('Content-Disposition: attachment;filename="'.$savefile.'.xls"');        
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");        
header('Cache-Control: max-age=0');        
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');        
$objWriter->save('php://output');

 源数据,和获取的都没问题,excel类是官网下的,我项目excel导入还用这个这个包啊,应该没问题的。  

转为gbk看下,另iconv转火星文和繁体字会有问题        
$vv = mb_convert_encoding($vv =, "GBK","UTF-8");

$vv =,  什么意思?
笔误,$vv         
过不了呢、
extension=php_mbstring.dll把这个扩展开了
php 的extension=php_mbstring.dll 开启了,重启apache,导出没有报错,但还是乱码    
header("Content-Type: application/vnd.ms-excel; charset=UTF-8"); 注释掉这句看看

对,有转回去了     
我前面说了,我单独测试你的代码段是没有问题的。  
所以问题可能出在别的地方:比如传入的数据、从表中读取的数据、甚至是你使用的phpexcel类    

include 'Plugin/PHPExcel/Classes/PHPExcel.php';
//        import('Org.Util.PHPExcel.IOFactory');
//        import('PHPExcel.Util.PHPExcel.Reader.Excel5');$data = array(  array('中','文','c'),  array('a','b','c'),  array('a','b','c'),);
$sheetname = '123';
$savefile = time();        
$objPHPExcel = new PHPExcel();        
//Excel内容        
foreach($data as $k => $v){            
$obj=$objPHPExcel->setActiveSheetIndex(0);            
$row=$k+1;//行            
$nn=0;            
foreach($v as $vv){                
$col=chr(65+$nn);//列$vv = iconv('gbk', 'utf-8', $vv);                
$obj->setCellValue($col.$row,$vv);//列,行,值                
$nn++;            
}        
}        
$objPHPExcel->getActiveSheet()->setTitle($sheetname);        
$objPHPExcel->setActiveSheetIndex(0);        
header('Content-Type: application/vnd.ms-excel');        
header('Content-Disposition: attachment;filename="'.$savefile.'.xls"');        
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");        
header('Cache-Control: max-age=0');        
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');        
$objWriter->save('php://output');

 我弄了一组测试数据,导出还是乱码啊?你不是测试没有问题吗?

好吧,我导出来了,exportexcel重写了,还是这个方法写的有问题,还是谢谢你们啊。

从图中可看到第5、11行都有错误信息  
你可把标题去掉,只保留数据体,进行测试  
exportExcel 中把这句也注释掉  
$objPHPExcel->getActiveSheet()->setTitle($sheetname);  

从图中可看到第5、11行都有错误信息   

你可把标题去掉,只保留数据体,进行测试  
exportExcel 中把这句也注释掉  
$objPHPExcel->getActiveSheet()->setTitle($sheetname);

还是不行哦  

function exportexcel($data=array(),$title=array(),$filename='report'){    
header("Content-type:application/octet-stream");    
header("Accept-Ranges:bytes");    
header("Content-type:application/vnd.ms-excel");      
header("Content-Disposition:attachment;filename=".$filename.".xls");    
header("Pragma: no-cache");    header("Expires: 0");    
//导出xls 开始    if (!empty($title)){        
foreach ($title as $k => $v) {            
$title[$k]=iconv("UTF-8", "GB2312",$v);        
}        
$title= implode("\t", $title);        
echo "$title\n";    }    
if (!empty($data)){        
foreach($data as $key=>$val){            
foreach ($val as $ck => $cv) {                
$data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);            
}            
$data[$key]=implode("\t", $data[$key]);                    
}       
echo implode("\n",$data);    
} 
}

我用上面的方法导出来没问题,问题结果是每组数据都在每行excel表格A格中,没有按列排开。能不能帮我改改

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version