当前位置:首页 > CMS教程 > Discuz > 列表

在disucz中使用PHPExcel,导入电子表格

发布:smiling 来源: PHP粉丝网  添加日期:2014-11-19 10:13:02 浏览: 评论:0 

在做discuz二次开发的时候,有个需求是导入产品卡密积分的Excel表格,discuz采用的是php语言开发,关于Excel方面的操作,当然要借助PHPExcel项目了.

PHPExcel - OpenXML - Read, Write and Create Excel documents in PHP - Spreadsheet engine

1、下载PHPExcel项目

地址http://phpexcel.codeplex.com/

2、在source/include/中创建目录PHPExcel

在disucz中使用PHPExcel,导入电子表格.

3、在discuz源代码中引用PHPExcel.php,需要先注销discuz原有的autoload,然后再注册.

  1. spl_autoload_unregister(array('core', 'autoload')); 
  2. include DISCUZ_ROOT.'./source/include/PHPExcel/PHPExcel.php'; 
  3. include DISCUZ_ROOT.'./source/include/PHPExcel/PHPExcel/IOFactory.php'; 
  4. spl_autoload_register(array('core', 'autoload')); 

4、读取Excel电子表格内容,下面示例.

  1. $objReader = PHPExcel_IOFactory::createReader('Excel2007');  
  2. $objReader->setReadDataOnly(true);  
  3. $objPHPExcel = $objReader->load($filename);  
  4. $objWorksheet = $objPHPExcel->getActiveSheet();  
  5. $highestRow = $objWorksheet->getHighestRow(); 
  6. $highestColumn = $objWorksheet->getHighestColumn(); 
  7. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); 
  8. $excelData = array();   
  9. for($row = 1; $row <= $highestRow; $row++){ 
  10. $excelrow = array(); 
  11. for ($col = 0; $col < $highestColumnIndex; $col++){ 
  12. $cellValue = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); 
  13. $cellValue = trim($cellValue); 
  14. if($col == 0 && emptyempty($cellValue)){ 
  15. break; 
  16. } 
  17. if($col == 6 || $col == 9){ 
  18. $cellValue=gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($cellValue)); 
  19. } 
  20. //一般第一行为字段;如果为单元格内容为空,说明字段结束,修正实际的栏目数量 
  21. if($row == 1 && emptyempty($cellValue)){ 
  22. $highestColumnIndex = $col; 
  23. continue; //开源软件:phpfensi.com 
  24. } 
  25. $excelrow[] = $cellValue; 
  26. } 
  27. if(emptyempty($excelrow)){ 
  28. break; 
  29. } 
  30. if($row == 1){ 
  31. continue; 
  32. } 
  33. $excelData[] = $excelrow; 
  34. }
  35. }

Tags: disucz电子表格 PHPExcel

分享到: