Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial php excel 导出乱码问题

php excel 导出乱码问题

May 26, 2018 am 11:12 AM
excel php Garbled characters Export


/**     
* 用于生成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);             
}
Copy after login

以上是我代码,我用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');
Copy after login

对,有转回去了

我前面说了,我单独测试你的代码段是没有问题的。
所以问题可能出在别的地方:比如传入的数据、从表中读取的数据、甚至是你使用的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');
Copy after login

源数据,和获取的都没问题,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');
Copy after login

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

好吧,我导出来了,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);    
} 
}
Copy after login

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

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles