search
HomeBackend DevelopmentPHP Tutorial使用phpexcel导出excel乱码

使用phpexcel导出excel乱码

Jun 23, 2016 pm 01:54 PM
excelphpexcelGarbled charactersExport

数据库和页面都是utf8。
  header('Content-Type: application/vnd.ms-excel;');
header('Content-Disposition: attachment;filename='.$filename.'.xls');
header('Cache-Control: max-age=0');
   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  $objWriter->save('php://output');  //
导出后,打开execel是乱码的。
本地window下导出的话没问题,上传到服务器上导出,就是乱码。
直接var_dump($objWreter)到页面,发现不会乱码。
  header('Content-Type: application/vnd.ms-excel;charset=gb2312')也还是乱码;
这个乱码是什么问题


回复讨论(解决方案)

在header() 前面加上ob_end_clean() 函数, 清除缓冲区, 这样就不会乱码了!
ob_end_clean();//清除缓冲区,避免乱码
header('Content-Type: application/vnd.ms-excel');
.....
.....

$objWriter->save('php://output'); 输出的是二进制文档流,就和图片一样不存在字符集的问题
用 excel 打开是出现乱码,是因为文件中含有不能被他识别的内容
这多半是包含了 php 的错误信息
你可以截个图贴上来看看,也可以以把 xls 文件放到网盘上

在header() 前面加上ob_end_clean() 函数, 清除缓冲区, 这样就不会乱码了!
ob_end_clean();//清除缓冲区,避免乱码
header('Content-Type: application/vnd.ms-excel');
.....
.....




的确是这问题,伤不起的缓冲区

$objWriter->save('php://output'); 输出的是二进制文档流,就和图片一样不存在字符集的问题
用 excel 打开是出现乱码,是因为文件中含有不能被他识别的内容
这多半是包含了 php 的错误信息
你可以截个图贴上来看看,也可以以把 xls 文件放到网盘上





在header() 前面加上ob_end_clean() 函数, 清除缓冲区, 这样就不会乱码了!
ob_end_clean();//清除缓冲区,避免乱码
header('Content-Type: application/vnd.ms-excel');
.....
.....




的确是这问题,伤不起的缓冲区

没用,我用的是本地测试的,唉!本地本来就可以的,大意了

你的 A1 单元格处的内容就不对
请检查是否有多余的输出

上下代码
/*--------------设置表头信息------------------*/
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'a')
            ->setCellValue('B1', 'b')
            ->setCellValue('C1', 'c')
            ->setCellValue('D1', 'd')
            ->setCellValue('E1', 'e')
            ->setCellValue('F1','f')
            ->setCellValue('G1','g')
            ->setCellValue('H1','h')
            ->setCellValue('I1',i')
            ->setCellValue('J1','f');
/*--------------开始从数据库提取信息插入Excel表中------------------*/
$i=2; //定义一个i变量,目的是在循环输出数据是控制行数
for($j=0;$j //  $rm = iconv("GB2312","UTF-8",$rs[1]);  //对字符进行编码将数据库里GB2312的中文字符转换成UTF-8格式
  $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue("A".$i, $result[$j]['ori_stu_name'])
            ->setCellValue("B".$i, $result[$j]['ori_stu_candidateNum'])
            ->setCellValue("C".$i, $result[$j]['ori_stu_sex'])
            ->setCellValue("D".$i, $result[$j]['ori_stu_id_card'])
            ->setCellValue("E".$i, $result[$j]['ori_stu_institution'])
            ->setCellValue('F'.$i, $result[$j]['ori_stu_specialty'])
            ->setCellValue('G'.$i, $result[$j]['ori_stu_phone'])
            ->setCellValue('H'.$i, $result[$j]['ori_stu_isMember'])
            ->setCellValue('I'.$i, $result[$j]['ori_stu_domicile'])
            ->setCellValue('J'.$i, $result[$j]['ori_stu_isReport']);         
            $i++;
 }

/*--------------下面是设置其他信息------------------*/
$objPHPExcel->getActiveSheet()->setTitle('学生表');      //设置sheet的名称
$objPHPExcel->setActiveSheetIndex(0);                            //设置sheet的起始位置
$filename = date('Y-m',time())."信息表";
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename='.$filename.'.xls');
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');  //这里生成excel后会弹出下载

你的 A1 单元格处的内容就不对
请检查是否有多余的输出



我上代码吧
Vendor("Excel.PHPExcel");            Vendor("Excel.PHPExcel.IOFactory");             $objPHPExcel = new PHPExcel();               $db=M("student_info");            $where="where fsi_logistics.ori_log_stuCandidateNum = fsi_student_info.ori_stu_candidateNum";            $sql="select logistics.*,student_info.ori_stu_name  from student_info,logistics ".$where;			$result= $db->query($sql); 			$objPHPExcel->setActiveSheetIndex(0)			            ->setCellValue('A1', '姓名')			            ->setCellValue('B1', '考生号')			            ->setCellValue('C1', '商品')			            ->setCellValue('D1', '价格');			$i=2;			for($j=0;$j<count($result);$j++){						  $objPHPExcel->setActiveSheetIndex(0)			            ->setCellValue("A".$i, $result[$j]['ori_stu_name'])			            ->setCellValue("B".$i, $result[$j]['ori_log_stuCandidateNum'])			            ->setCellValue("C".$i, $result[$j]['product'])			            ->setCellValue("D".$i, $result[$j]['price']);         			            $i++;			 }					$objPHPExcel->getActiveSheet()->setTitle('学生表'); 			$objPHPExcel->setActiveSheetIndex(0);   			$filename = date('Y-m',time())."生活用品表";			ob_end_clean() ;            header('Content-Type: application/vnd.ms-excel');            header('Content-Disposition: attachment;filename='.$filename.'.xls');            header('Cache-Control: max-age=0');            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');            $objWriter->save('php://output');            exit;   

没有其它输出了呀,在winddow下导出是正常的

我已经解决了,bom头的问题,谢谢你们了

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor