php:php中應用excel的簡單介紹

來源:互聯網
上載者:User
php:php中使用excel的簡單介紹

在工作中需要處理多語言的翻譯問題,翻譯都是寫在excel表格裡面。為了處理方便我就保留中文和英文兩列。

這樣需要將這些資料從excel中取出來,然乎儲存在excel的數組中,通過使用迴圈數組將相應的資料放入到資料庫中。

所以工作的第一步就是要將資料從excel中取出來。這裡我使用到了一個開源php處理excel類:phpexcel. 該項目的詳細資料 http://phpexcel.codeplex.com/ 。

我目前使用的是phpexcel1.7.3版本, 解壓縮后里面有一個PHPExcel和PHPExcel.php檔案。

我們主要使用那個PHP檔案。見檔案目錄結構

這個版本據說是可以支援excel2007,但是我使用2007編輯的xlsx是無法獲得該庫的支援。於是乎我就將它轉化為2003。感覺支援地很好。

下面介紹一下具體的使用:

require_once('./phpexcel1.7.3/PHPExcel.php');$php_excel_obj = new PHPExcel();$php_reader = newPHPExcel_Reader_Excel2007();if(!$php_reader->canRead($file_name)){       $php_reader= new PHPExcel_Reader_Excel5();       if(!$php_reader->canRead($file_name)){              echo'NO Excel!';       }}$php_excel_obj = $php_reader->load($file_name);$current_sheet =$php_excel_obj->getSheet(0);

上面的主要功能是初始化相關的excel類,並裝載excel第一個sheet

$all_column =$current_sheet->getHighestColumn();$all_row =$current_sheet->getHighestRow();

以上分別獲得該表格的最大列值(字母表示如:‘G’),和最大的行數(數值表示)

下面將使用迴圈來講excel裡面的資料讀到excel中:

$all_arr = array();$c_arr = array();//字元對照表for($r_i = 1; $r_i<=$all_row; $r_i++){       $c_arr= array();       for($c_i= 'A'; $c_i<= 'B'; $c_i++){              $adr= $c_i . $r_i;              $value= $current_sheet->getCell($adr)->getValue();              if($c_i== 'A' && empty($value) )  break;              if(is_object($value))  $value= $value->__toString();              $c_arr[$c_i]= $value;       }       $c_arr&& $all_arr[] =  $c_arr;}

下面簡單地介紹一下phpexcel的寫操作,這個操作經常用於將資料庫中的資料匯入到excel中,便於展示和做成更美觀的效果。

require_once('./phpexcel1.7.3/PHPExcel.php');$excel_obj = new PHPExcel();$objWriter = newPHPExcel_Writer_Excel5($excel_obj); $excel_obj->setActiveSheetIndex(0);$act_sheet_obj=$excel_obj->getActiveSheet();$act_sheet_obj->setTitle('sheet');$act_sheet_obj->setCellValue('A1', '字串內容');$act_sheet_obj->setCellValue('A2', 26); $file_name = "output.xls";$objWriter->save($file_name);

代碼很簡單, 首先初始化相關的excel寫類,然後寫入資料,最後儲存為xls檔案。

輸出的效果見圖

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.