在做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; //開源軟件:Vevb.com
- }
- $excelrow[] = $cellValue;
- }
- if(emptyempty($excelrow)){
- break;
- }
- if($row == 1){
- continue;
- }
- $excelData[] = $excelrow;
- }
- }
新聞熱點
疑難解答