https://github.com/PHPOffice/PHPExcelphp
include "/lib/PHPExcel/Classes/PHPExcel/IOFactory.php";//讀取Excel所需文件 include "/lib/PHPExcel/Classes/PHPExcel.php"; //寫入excel所需的類文件
private $fileName = null; private $sheet = 0; /** * myExcelUtil構造函數,構造參數爲文件路徑 * * @param String $fileName */ public function __construct($fileName = null) { $this->fileName = $fileName; }
/** * 讀取一個sheet表,默認第一個 * */ public function readSheet() { $this->readSheetBySheet(0); } /** * 讀取一個sheet表 * @param String|int $sheetIndex,表名或索引 * @return array,二維數組 */ public function readSheetBySheet($sheetIndex = 0) { //$filename = 'xuehua04.xlsx'; date_default_timezone_set('PRC'); // 讀取excel文件 try { $inputFileType = PHPExcel_IOFactory::identify($this->fileName); $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($this->fileName); } catch (Exception $e) { die("加載文件發生錯誤:" . pathinfo($this->fileName, PATHINFO_BASENAME) . ":" . $e->getMessage()); } // 肯定要讀取的sheet try { $sheet = $objPHPExcel->getSheet($sheetIndex); $this->setSheet($sheet->getTitle()); } catch (PHPExcel_Exception $e) { } $highestRow = $sheet->getHighestRow(); $highestColumn = $sheet->getHighestColumn(); $outputArray = array(); // 獲取一行的數據 for ($row = 1; $row <= $highestRow; $row++) { // Read a row of data into an array $rowData = $sheet->rangeToArray("A" . $row . ":" . $highestColumn . $row, NULL, TRUE, FALSE); //這裏獲得的rowData都是一行的數據,獲得數據後自行處理,咱們這裏只打出來看看效果 $outputArray[] = $rowData[0]; //print_r($rowData); } return $outputArray; }
/** * 向指定表指定位置插入數據 * @param String|int $sheetIndex,表名或索引 * @param int $row,行 * @param int $col,列 * @param string $value,值 */ public function addCellValueByRC($sheetIndex = 0, $row = 0, $col = 0, $value = "") { $inputArray = $this->readSheetBySheet(0); $inputArray[$row - 1][$col - 1] = $value; $objPHPExcel = new PHPExcel(); //實例化一個PHPExcel()對象 try { $objSheet = $objPHPExcel->getActiveSheet(); } catch (PHPExcel_Exception $e) { } //選取當前的sheet對象 $objSheet->setTitle($this->getSheet()); //對當前sheet對象命名 //常規方式:利用setCellValue()填充數據 //$objSheet->setCellValue("A1", "張三")->setCellValue("B1", "李四"); //利用setCellValues()填充數據 /*$arrayLength = count($inputArray); $basic = 'A'; for($i = 0;$i<$arrayLength;$i++){ foreach ($inputArray[$i] as $key => $d){ $objSheet->setCellValue($basic.($i+1), $d); $basic++; } $basic = 'A'; }*/ //取巧模式:利用fromArray()填充數據 try { $objSheet->fromArray($inputArray); } catch (PHPExcel_Exception $e) { } //利用fromArray()直接一次性填充數據*/ try { $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); } catch (PHPExcel_Reader_Exception $e) { } //設定寫入excel的類型 try { $objWriter->save($this->getFileName()); } catch (PHPExcel_Writer_Exception $e) { } //保存文件 }