博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ThinkPHP+PHPExcel[导入][导出]实现方法
阅读量:5967 次
发布时间:2019-06-19

本文共 6298 字,大约阅读时间需要 20 分钟。

hot3.png

/**     +----------------------------------------------------------     * Export Excel |     +----------------------------------------------------------     * @param $expTitle     string File name     +----------------------------------------------------------     * @param $expCellName  array  Column name     +----------------------------------------------------------     * @param $expTableData array  Table data     +----------------------------------------------------------     */    public function exportExcel($expTitle,$expCellName,$expTableData){        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称        $fileName = $_SESSION['loginAccount'].date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定        $cellNum = count($expCellName);        $dataNum = count($expTableData);        vendor("PHPExcel.PHPExcel");        $objPHPExcel = new PHPExcel();        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');                $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));          for($i=0;$i<$cellNum;$i++){            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);         }           // Miscellaneous glyphs, UTF-8           for($i=0;$i<$dataNum;$i++){          for($j=0;$j<$cellNum;$j++){            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);          }                     }                  header('pragma:public');        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');          $objWriter->save('php://output');         exit;       }         /**     +----------------------------------------------------------     * Import Excel |     +----------------------------------------------------------     * @param  $file   upload file $_FILES     +----------------------------------------------------------     * @return array   array("error","message")     +----------------------------------------------------------          */       public function importExecl($file){         if(!file_exists($file)){             return array("error"=>0,'message'=>'file not found!');        }         Vendor("PHPExcel.PHPExcel.IOFactory");         $objReader = PHPExcel_IOFactory::createReader('Excel5');         try{            $PHPReader = $objReader->load($file);        }catch(Exception $e){}        if(!isset($PHPReader)) return array("error"=>0,'message'=>'read error!');        $allWorksheets = $PHPReader->getAllSheets();        $i = 0;        foreach($allWorksheets as $objWorksheet){            $sheetname=$objWorksheet->getTitle();            $allRow = $objWorksheet->getHighestRow();//how many rows            $highestColumn = $objWorksheet->getHighestColumn();//how many columns            $allColumn = PHPExcel_Cell::columnIndexFromString($highestColumn);            $array[$i]["Title"] = $sheetname;             $array[$i]["Cols"] = $allColumn;             $array[$i]["Rows"] = $allRow;             $arr = array();            $isMergeCell = array();            foreach ($objWorksheet->getMergeCells() as $cells) {//merge cells                foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {                    $isMergeCell[$cellReference] = true;                }            }            for($currentRow = 1 ;$currentRow<=$allRow;$currentRow++){                 $row = array();                 for($currentColumn=0;$currentColumn<$allColumn;$currentColumn++){;                                    $cell =$objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);                    $afCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn+1);                    $bfCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn-1);                    $col = PHPExcel_Cell::stringFromColumnIndex($currentColumn);                    $address = $col.$currentRow;                    $value = $objWorksheet->getCell($address)->getValue();                    if(substr($value,0,1)=='='){                        return array("error"=>0,'message'=>'can not use the formula!');                        exit;                    }                    if($cell->getDataType()==PHPExcel_Cell_DataType::TYPE_NUMERIC){                        $cellstyleformat=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat();                        $formatcode=$cellstyleformat->getFormatCode();                        if (preg_match('/^([$[A-Z]*-[0-9A-F]*])*[hmsdy]/i', $formatcode)) {                            $value=gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($value));                        }else{                            $value=PHPExcel_Style_NumberFormat::toFormattedString($value,$formatcode);                        }                                    }                    if($isMergeCell[$col.$currentRow]&&$isMergeCell[$afCol.$currentRow]&&!empty($value)){                        $temp = $value;                    }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$col.($currentRow-1)]&&empty($value)){                        $value=$arr[$currentRow-1][$currentColumn];                    }elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$bfCol.$currentRow]&&empty($value)){                        $value=$temp;                    }                    $row[$currentColumn] = $value;                 }                 $arr[$currentRow] = $row;             }             $array[$i]["Content"] = $arr;             $i++;        }         spl_autoload_register(array('Think','autoload'));//must, resolve ThinkPHP and PHPExcel conflicts        unset($objWorksheet);         unset($PHPReader);         unset($PHPExcel);         unlink($file);         return array("error"=>1,"data"=>$array);     }

 

转载于:https://my.oschina.net/yakoras/blog/826783

你可能感兴趣的文章
ORA-02266: 表中的唯一/主键被启用的外键引用
查看>>
Django的POST请求时因为开启防止csrf,报403错误,及四种解决方法
查看>>
Apache common-fileupload用户指南
查看>>
day-6 and day-7:面向对象
查看>>
IE维护(IEM)策略不再适用于IE10及后续IE版本
查看>>
Java7中的ForkJoin并发框架初探(下)—— ForkJoin的应用
查看>>
java中的重量级与轻量级概念
查看>>
Linux设备驱动工程师之路——硬件访问及混杂设备LED驱动
查看>>
进程和线程<一>
查看>>
远程算数程序——版本v1.0
查看>>
Mysql常见四种索引的使用
查看>>
说说Android桌面(Launcher应用)背后的故事(一)——揭开她神秘的面纱
查看>>
第一篇:zc706 开箱及开发环境搭建
查看>>
python-冒泡排序
查看>>
Mac下修改Hosts文件工具——Gas Mask
查看>>
协程函数应用
查看>>
CSU Double Shortest Paths 湖南省第十届省赛
查看>>
webgl像机世界
查看>>
php正则怎么使用(最全最细致)
查看>>
javascript数学运算符
查看>>