淺談PHP匯入EXCEL資料

來源:互聯網
上載者:User
淺談PHP匯入EXCEL檔案

PHP匯入excel的開源檔案有好幾個,我用的是phpExcelReader。

方法如下,直接上代碼:

$filename = $_FILES ['excel'] ['name'];$tmp_name = $_FILES ['excel'] ['tmp_name'];// 儲存上傳檔案if (move_uploaded_file ( $tmp_name, 'upload/' . $filename )) {    inputExcel ( $filename );}// 調用Readerrequire_once 'reader.php';// 建立 Reader$data = new Spreadsheet_Excel_Reader ();// 設定文本輸出編碼$data->setOutputEncoding ( 'utf-8' );// 讀取Excel檔案$data->read ( 'upload/' . $filename );// $data->sheets[0]['numRows']為Excel行數// $data->sheets[0]['numCols'] 為Excel列數for($i = 2; $i <= $data->sheets[0]['numRows']; $i ++) {    // 從儲存格中擷取資料    $a = mysql_real_escape_string ( $data->sheets [0] ['cells'] [$i] [1] );    $b = mysql_real_escape_string ( $data->sheets [0] ['cells'] [$i] [2] );    $c = mysql_real_escape_string ( $data->sheets [0] ['cells'] [$i] [3] );    $d = mysql_real_escape_string ( $data->sheets [0] ['cells'] [$i] [4] );}

?

這段代碼的功能就是上傳一個excel檔案並擷取其中資料,值得說明的是:

1、excel表格中不要有半形的(小括弧)和[中括弧],因為它擷取資料的時候是直接儲存到一個數組,所以其中的(小括弧)和[中括弧]會影響數組的格式,並引發錯誤,我的做法是把它們替換成全形的(小括弧)和【中括弧】。

2、如果要把從excel中取出的值和資料庫互動的話,我在這裡mysql_real_escape_string (data)直接做了轉義,防止執行資料庫時因為一些符號引起的錯誤。

3、當excel中的資料量比較大的時候,在往資料庫中插入的時候,注意sql語句的長度,PHP字串的長度限制與php.ini中的配置和電腦記憶體有關。

4、$data->setOutputEncoding ( 'utf-8' )可解決中文亂碼的問題。

?

  • 聯繫我們

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