在disucz中使用PHPExcel,导入电子表格
在做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,然后再注册.
- spl_autoload_unregister(array('core', 'autoload'));
- include DISCUZ_ROOT.'./source/include/PHPExcel/PHPExcel.php';
- include DISCUZ_ROOT.'./source/include/PHPExcel/PHPExcel/IOFactory.php';
- spl_autoload_register(array('core', 'autoload'));
4、读取Excel电子表格内容,下面示例.
- $objReader = PHPExcel_IOFactory::createReader('Excel2007');
- $objReader->setReadDataOnly(true);
- $objPHPExcel = $objReader->load($filename);
- $objWorksheet = $objPHPExcel->getActiveSheet();
- $highestRow = $objWorksheet->getHighestRow();
- $highestColumn = $objWorksheet->getHighestColumn();
- $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
- $excelData = array();
- for($row = 1; $row <= $highestRow; $row++){
- $excelrow = array();
- for ($col = 0; $col < $highestColumnIndex; $col++){
- $cellValue = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
- $cellValue = trim($cellValue);
- if($col == 0 && emptyempty($cellValue)){
- break;
- }
- if($col == 6 || $col == 9){
- $cellValue=gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($cellValue));
- }
-
- if($row == 1 && emptyempty($cellValue)){
- $highestColumnIndex = $col;
- continue;
- }
- $excelrow[] = $cellValue;
- }
- if(emptyempty($excelrow)){
- break;
- }
- if($row == 1){
- continue;
- }
- $excelData[] = $excelrow;
- }
- }