php處理Excel

遇到問題

平時在工做中,時常會出現將數據庫表導出爲Excel或者將Excel導入數據庫表的需求。這一需求早早就已經實現過了,爲了方便導入導出,我將其封裝成了兩個方法,做爲記錄。php

代碼實現

phpexcel類庫的引用

phpexcel擁有強大的Excel處理能力,在packagist上已經擁有數百萬次的下載量,不過實話實說,excel的處理速度仍然是很是慢,數據量較大時慎重使用。在packagist上下載或者直接用composer require phpoffice/phpexcel以後,即可以使用phpexcel了。數據庫

導出成爲Excel

在絕大多數狀況下,導出excel其實就是將二維數組轉化爲表格。數組

/**
     * @param $name string 要保存的Excel的名字
     * @param $ret_data 轉換爲表格的二維數組
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    function exportExcel($name, $ret_data){
        $objPHPExcel = new \PHPExcel\PHPExcel();
        //設置表格
        $objPHPExcel->getProperties()->setCreator($name)
                ->setLastModifiedBy($name)
                ->setTitle("Office 2007 XLSX Test Document")
                ->setSubject("Office 2007 XLSX Test Document")
                ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");
        //填充數據
        foreach ($ret_data as $key => $row) {
            $num = $key + 1;
            //$row = array_values($row);
            $i=0;
            foreach ($row as $key2 => $value2) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( \PHPExel\Cell::stringFromColumnIndex($i). ($num), $value2);
                $i++;
            }
        }
        //設置表格並輸出
        $objPHPExcel->getActiveSheet()->setTitle($name);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename={$name}.xls");
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel\IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

導入Excel

同理,導入Excel其實就是將Excel的數據轉化成爲二維數組,這就要求Excel必須符合格式。app

function getRows($inputFileName)
    {
        if (!file_exists($inputFileName)) {
            throw new Exception("File not existed");
        }
        $inputFileType = \PHPExcel\IOFactory::identify($inputFileName);
        $objReader = \PHPExcel\IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel\Cell::columnIndexFromString($highestColumn);//總列數
        $row = 1;
        $curr = array();
        while ($row <= $highestRow) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $value = str_replace(array("\n\r", "\n", "\r"), "", $objWorksheet->getCellByColumnAndRow($col, $row)->getValue());
                $curr[$row][] = $value;
            }
            $row++;
        }
        array_shift($curr);//第一行通常是字段名(Excel中列的標題),導入時要移除
        return $curr;
    }

其餘

  • 導出時保存的格式是xlsx,想要改爲其餘格式須要傳入不一樣的參數。
  • 導入時若是有多個sheet時須要在上次打開時在要導入的sheet頁(以保證當前sheet爲activeSheet)關閉,或者根據sheet名在程序中選擇sheet。
相關文章
相關標籤/搜索