php處理Excel步驟介紹

來源:互聯網
上載者:User

標籤:

php處理Excel步驟介紹

遇到問題

平時在工作中,時常會出現將資料庫表匯出為Excel或者將Excel匯入資料庫表的需求。這一需求早早就已經實現過了,為了方便匯入匯出,兄弟連www.itxdl.cn將其分裝成了兩個方法作為記錄。

 

代碼實現

phpexcel類庫的引用

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

 

匯出成為Excel

在絕大多數情況下,匯出excel其實就是將二位元組轉化為表格。

 

    use namespace PHPExcel;

    /**

     * @param $name string 要儲存的Excel的名字

     * @param $ret_data 轉換為表格的二維數組

     * @throws PHPExcel_Exception

     * @throws PHPExcel_Reader_Exception

     */

    function exportExcel($name, $ret_data){

        $objPHPExcel = new 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( 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必須符合格式。

 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", "\n\r", "\r"), "", $objWorksheet->getCellByColumnAndRow($col, $row)->getValue());

                $curr[$row][] = $value;

            }

            $row++;

        }

        array_shift($curr);//第一行一般是欄位名(Excel中列的標題),匯入時要移除

        return $curr;

}

 

其他

匯出時儲存的格式是xlsx,想要改成其他格式需要傳入不同的參數。

匯入時如果有多個sheet時需要在上次開啟時在要匯入的sheet頁(以保證當前sheet為activeSheet)關閉,或者根據sheet名在程式中選擇sheet。

php處理Excel步驟介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.