手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆

PHP导入导出Excel方法

首页 > PHP >

原作者:冰山上的播客
看到这篇文章的时候,很是惊讶原作者的耐心,虽然我们在平时用的也有一些,但没有作者列出来的全,写excel的时候,我用过pear的库,也用过pack压包的头,同样那些利用smarty等作的简单替换xml的也用过,csv的就更不用谈了。呵呵。(COM方式不讲了,这种可读的太多了,我也写过利用wps等进行word等的生成之类的文章 )
但是在读的时候,只用过一种,具体是什么忘了,要回去翻代码了。因为采用的是拿来主义,记不住。
原文地址:http://xinsync.xju.edu.cn/index.php/archives/3858
原文内容:

最近因项目需要,需要开发一个模块,把系统中的一些数据导出成Excel,修改后再导回系统。就趁机对这个研究了一番,下面进行一些总结
基本上导出的文件分为两种:
1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Excel的兼容能力强,能够正确打开而已。修改这种文件后再保存,通常会提示你是否要转换成Excel文件。
优点:简单。
缺点:难以生成格式,如果用来导入需要自己分别编写相应的程序。
2:Excel格式,与类Excel相对应,这种方法生成的文件更接近于真正的Excel格式。

如果导出中文时出现乱码,可以尝试将字符串转换成gb2312,例如下面就把$yourStr从utf-8转换成了gb2312:
$yourStr = mb_convert_encoding(”gb2312″, “UTF-8″, $yourStr);

有网友指出上面的转换是错误的,确实,上面的参数顺序是iconv函数的,$yourStr应该是第一个参数。

下面详细列举几种方法。
一、PHP导出Excel

1:第一推荐无比风骚的PHPExcel,官方网站: http://www.codeplex.com/PHPExcel
导入导出都成,可以导出office2007格式,同时兼容2003。
下载下来的包中有文档和例子,大家可以自行研究。
抄段例子出来:

PHP代码
  1. <?php  
  2. /** 
  3. * PHPExcel 
  4. * 
  5. * Copyright (C) 2006 - 2007 PHPExcel 
  6. * 
  7. * This library is free software; you can redistribute it and/or 
  8. * modify it under the terms of the GNU Lesser General Public 
  9. * License as published by the Free Software Foundation; either 
  10. * version 2.1 of the License, or (at your option) any later version. 
  11. * 
  12. * This library is distributed in the hope that it will be useful, 
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of 
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
  15. * Lesser General Public License for more details. 
  16. * 
  17. * You should have received a copy of the GNU Lesser General Public 
  18. * License along with this library; if not, write to the Free Software 
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA 
  20. * 
  21. * @category   PHPExcel 
  22. * @package    PHPExcel 
  23. * @copyright  Copyright (c) 2006 - 2007 PHPExcel ( http://www.codeplex.com/PHPExcel) 
  24. * @license    http://www.gnu.org/licenses/lgpl.txt    LGPL 
  25. * @version    1.5.0, 2007-10-23 
  26. */  
  27.   
  28. /** Error reporting */  
  29. error_reporting(E_ALL);  
  30.   
  31. /** Include path **/  
  32. set_include_path(get_include_path() . PATH_SEPARATOR . ‘../Classes/’);  
  33.   
  34. /** PHPExcel */  
  35. include ‘PHPExcel.php’;  
  36.   
  37. /** PHPExcel_Writer_Excel2007 */  
  38. include ‘PHPExcel/Writer/Excel2007.php’;  
  39.   
  40. // Create new PHPExcel object  
  41. echo date(’H:i:s’) . ” Create new PHPExcel object\n”;  
  42. $objPHPExcel = new PHPExcel();  
  43.   
  44. // Set properties  
  45. echo date(’H:i:s’) . ” Set properties\n”;  
  46. $objPHPExcel->getProperties()->setCreator(”Maarten Balliauw”);  
  47. $objPHPExcel->getProperties()->setLastModifiedBy(”Maarten Balliauw”);  
  48. $objPHPExcel->getProperties()->setTitle(”Office 2007 XLSX Test Document”);  
  49. $objPHPExcel->getProperties()->setSubject(”Office 2007 XLSX Test Document”);  
  50. $objPHPExcel->getProperties()->setDescrīption(”Test document for Office 2007 XLSX, generated using PHP classes.”);  
  51. $objPHPExcel->getProperties()->setKeywords(”office 2007 openxml php”);  
  52. $objPHPExcel->getProperties()->setCategory(”Test result file”);  
  53.   
  54. // Add some data  
  55. echo date(’H:i:s’) . ” Add some data\n”;  
  56. $objPHPExcel->setActiveSheetIndex(0);  
  57. $objPHPExcel->getActiveSheet()->setCellValue(’A1′, ‘Hello’);  
  58. $objPHPExcel->getActiveSheet()->setCellValue(’B2′, ‘world!’);  
  59. $objPHPExcel->getActiveSheet()->setCellValue(’C1′, ‘Hello’);  
  60. $objPHPExcel->getActiveSheet()->setCellValue(’D2′, ‘world!’);  
  61.   
  62. // Rename sheet  
  63. echo date(’H:i:s’) . ” Rename sheet\n”;  
  64. $objPHPExcel->getActiveSheet()->setTitle(’Simple’);  
  65.   
  66. // Set active sheet index to the first sheet, so Excel opens this as the first sheet  
  67. $objPHPExcel->setActiveSheetIndex(0);  
  68.   
  69. // Save Excel 2007 file  
  70. echo date(’H:i:s’) . ” Write to Excel2007 format\n”;  
  71. $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);  
  72. $objWriter->save(str_replace(’.php’, ‘.xlsx’, __FILE__));  
  73.   
  74. // Echo done  
  75. echo date(’H:i:s’) . ” Done writing file.”;  

 


2、使用pear的Spreadsheet_Excel_Writer
下载地址: http://pear.php.net/package/Spreadsheet_Excel_Writer
此类依赖于OLE,下载地址:http://pear.php.net/package/OLE
需要注意的是导出的Excel文件格式比较老,修改后保存会提示是否转换成更新的格式。
不过可以设定格式,很强大。

PHP代码
  1. <?php  
  2. require_once ‘Spreadsheet/Excel/Writer.php’;  
  3.   
  4. // Creating a workbook  
  5. $workbook = new Spreadsheet_Excel_Writer();  
  6.   
  7. // sending HTTP headers  
  8. $workbook->send(’test.xls’);  
  9.   
  10. // Creating a worksheet  
  11. $worksheet =& $workbook->addWorksheet(’My first worksheet’);  
  12.   
  13. // The actual data  
  14. $worksheet->write(0, 0, ‘Name’);  
  15. $worksheet->write(0, 1, ‘Age’);  
  16. $worksheet->write(1, 0, ‘John Smith’);  
  17. $worksheet->write(1, 1, 30);  
  18. $worksheet->write(2, 0, ‘Johann Schmidt’);  
  19. $worksheet->write(2, 1, 31);  
  20. $worksheet->write(3, 0, ‘Juan Herrera’);  
  21. $worksheet->write(3, 1, 32);  
  22.   
  23. // Let’s send the file  
  24. $workbook->close();  
  25. ?>  

 

3:利用smarty,生成符合Excel规范的XMLHTML文件
支持格式,非常完美的导出方案。不过导出来的的本质上还是XML文件,如果用来导入就需要另外处理了。
详细内容请见rardge大侠的帖子:http://bbs.chinaunix.net/viewthread.php?tid=745757

需要注意的是如果导出的表格行数不确定时,最好在模板中把”ss:ExpandedColumnCount=”5″ ss:ExpandedRowCount=”21″”之类的东西删掉。

4、利用pack函数打印出模拟Excel格式的断句符号,这种更接近于Excel标准格式,用office2003修改后保存,还不会弹出提示,推荐用这种方法。
缺点是无格式。

PHP代码
  1. <?php  
  2. // Send Header  
  3. header(”Pragma: public”);  
  4. header(”Expires: 0″);  
  5. header(”Cache-Control: must-revalidate, post-check=0, pre-check=0″);  
  6. header(”Content-Type: application/force-download”);  
  7. header(”Content-Type: application/octet-stream”);  
  8. header(”Content-Type: application/download”);;  
  9. header(”Content-Disposition: attachment;filename=test.xls “);  
  10. header(”Content-Transfer-Encoding: binary “);  
  11. // XLS Data Cell  
  12.   
  13. xlsBOF();  
  14. xlsWriteLabel(1,0,”My excel line one”);  
  15. xlsWriteLabel(2,0,”My excel line two : “);  
  16. xlsWriteLabel(2,1,”Hello everybody”);  
  17.   
  18. xlsEOF();  
  19.   
  20. function xlsBOF() {  
  21. echo pack(”ssssss”, 0×809, 0×8, 0×0, 0×10, 0×0, 0×0);  
  22. return;  
  23. }  
  24. function xlsEOF() {  
  25. echo pack(”ss”, 0×0A, 0×00);  
  26. return;  
  27. }  
  28. function xlsWriteNumber($Row$Col$Value) {  
  29. echo pack(”sssss”, 0×203, 14, $Row$Col, 0×0);  
  30. echo pack(”d”, $Value);  
  31. return;  
  32. }  
  33. function xlsWriteLabel($Row$Col$Value ) {  
  34. $L = strlen($Value);  
  35. echo pack(”ssssss”, 0×204, 8 + $L$Row$Col, 0×0, $L);  
  36. echo $Value;  
  37. return;  
  38. }  
  39. ?>  
  40. 不过笔者在64位linux系统中使用时失败了,断句符号全部变成了乱码。  
  41.   
  42. 5、使用制表符、换行符的方法  
  43. 制表符”\t”用户分割同一行中的列,换行符”\t\n”可以开启下一行。  
  44. <?php  
  45. header(”Content-Type: application/vnd.ms-execl”);  
  46. header(”Content-Disposition: attachment; filename=myExcel.xls”);  
  47. header(”Pragma: no-cache”);  
  48. header(”Expires: 0″);  
  49. /*first line*/  
  50. echo “hello”.”\t”;  
  51. echo “world”.”\t”;  
  52. echo “\t\n”;  
  53.   
  54. /*start of second line*/  
  55. echo “this is second line”.”\t”;  
  56. echo “Hi,pretty girl”.”\t”;  
  57. echo “\t\n”;  
  58. ?>  

 

6、使用com
如果你的PHP可以开启com模块,就可以用它来导出Excel文件

PHP代码
  1. <?PHP  
  2. $filename = “c:/spreadhseet/test.xls”;  
  3. $sheet1 = 1;  
  4. $sheet2 = “sheet2″;  
  5. $excel_app = new COM(”Excel.application”) or Die (”Did not connect”);  
  6. print “Application name: {$excel_app->Application->value}\n” ;  
  7. print “Loaded version: {$excel_app->Application->version}\n”;  
  8. $Workbook = $excel_app->Workbooks->Open(”$filename”) or Die(”Did not open $filename $Workbook”);  
  9. $Worksheet = $Workbook->Worksheets($sheet1);  
  10. $Worksheet->activate;  
  11. $excel_cell = $Worksheet->Range(”C4″);  
  12. $excel_cell->activate;  
  13. $excel_result = $excel_cell->value;  
  14. print “$excel_result\n”;  
  15. $Worksheet = $Workbook->Worksheets($sheet2);  
  16. $Worksheet->activate;  
  17. $excel_cell = $Worksheet->Range(”C4″);  
  18. $excel_cell->activate;  
  19. $excel_result = $excel_cell->value;  
  20. print “$excel_result\n”;  
  21. #To close all instances of excel:  
  22. $Workbook->Close;  
  23. unset($Worksheet);  
  24. unset($Workbook);  
  25. $excel_app->Workbooks->Close();  
  26. $excel_app->Quit();  
  27. unset($excel_app);  
  28. ?>  


一个更好的例子: http://blog.chinaunix.net/u/16928/showart_387171.html

 

一、PHP导入Excel

1:还是用PHPExcel,官方网站: http://www.codeplex.com/PHPExcel。

2:使用PHP-ExcelReader,下载地址: http://sourceforge.net/projects/phpexcelreader
举例:

PHP代码
  1. <?php  
  2. require_once ‘Excel/reader.php’;  
  3.   
  4. // ExcelFile($filename, $encoding);  
  5. $data = new Spreadsheet_Excel_Reader();  
  6.   
  7. // Set output Encoding.  
  8. $data->setOutputEncoding(’utf8′);  
  9.   
  10. $data->read(’ jxlrwtest.xls’);  
  11.   
  12. error_reporting(E_ALL ^ E_NOTICE);  
  13.   
  14. for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {  
  15. for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {  
  16. echo “\”".$data->sheets[0]['cells'][$i][$j].”\”,”;  
  17. }  
  18. echo “\n”;  
  19. }  
  20.   
  21. ?>  

 




本站采用创作共享版权协议, 要求署名、非商业和保持一致. 本站欢迎任何非商业应用的转载, 但须注明出自"易栈网-膘叔", 保留原始链接, 此外还必须标注原文标题和链接.

Tags: php, excel, 转摘

« 上一篇 | 下一篇 »

只显示10条记录相关文章

使用PHP得到所有的HTTP请求头 (浏览: 62675, 评论: 3)
我为什么会选用phpstorm (浏览: 52517, 评论: 5)
快速生成目录树 (浏览: 46707, 评论: 7)
通过file_get_contents来Post数据的实例 (浏览: 46283, 评论: 5)
PHP的XSS攻击过滤函数 (浏览: 42614, 评论: 2)
PHP中Eval的作用 (浏览: 41549, 评论: 4)
超详细:在Mac OS X中配置Apache + PHP + MySQL (浏览: 40227, 评论: 1)
PHP常见错误(二) (浏览: 39690, 评论: 1)
PHP sendmail (浏览: 37839, 评论: 7)
几个ZendStudio使用教程 (浏览: 36363, 评论: 0)

3条记录访客评论

不错哦,讲的很好。
http://www.ttgjx.com

Post by 网友 on 2011, March 12, 10:00 AM 引用此文发表评论 #1

感谢您的提出。确实,上面的顺序是iconv函数的。当是我在转载的时候也没有注意。已经更新

Post by gouki on 2010, June 9, 10:31 AM 引用此文发表评论 #2

“$yourStr = mb_convert_encoding(”gb2312″, “UTF-8″, $yourStr)”
参数顺序错了,应该是:
$yourStr = mb_convert_encoding($yourStr,”gb2312″, “UTF-8″ )

Post by hally on 2010, June 9, 2:00 AM 引用此文发表评论 #3


发表评论

评论内容 (必填):