Drupal讀取Excel並匯入到mysql資料庫程式碼

來源:互聯網
上載者:User

Drupal 通過Library 調用 PHPExcl
將PHPExcel 下載後,上傳到Drupal目錄:sites/all/libraries/PHPExcel

如果你的項目中安裝了libraries模組,可以通過libraries_load($name);來調用。

如果沒有安裝libraries模組,可以簡單的使用下列代碼來調用:

 代碼如下 複製代碼

require("sites/all/libraries/PHPExcel/PHPExcel/IOFactory.php");

注意為了確保Excel全部匯入,程式可以會話很長的時間來進行。

所以在代碼開頭部分加入:

 代碼如下 複製代碼

set_time_limit(0);

來確保已耗用時間不受限制。

Drupal 讀取Excel並匯入到資料庫
Drupal 實現上傳Excel檔案後,讀取Excel 內容,寫入到資料庫,列印匯入結果訊息。

歸納起來有這樣幾點:

Drupal 讀取Excel 多行多列內容,列數從1到n,行數也是1到n。
Drupal 根據資料庫結構 n 個欄位分別用於存放Excel 1到n列,如果Excel 的列數很多,可以把n列值存放在1個欄位中。
這裡我解決的是Excel n列值存放到MySQL n個欄位中(n不是很大)

這就是在Drupal最後提交上傳檔案後的函數:

 代碼如下 複製代碼
<?php
function excel_upload_form_submit($form, &$form_state) {
  set_time_limit(0);
  $timestamp = time();
  // 確保Excel檔案上傳了
  if ($file = file_save_upload(‘file’)) {
    $row = 0; //解析行數
    $paseRows = 0; //跳過行數 沒有值的行
    $insertRows = 0; //插入行數
    $table = array(
      ‘dbfield1′,
      ‘dbfield2′,
      ‘dbfield3,
      ‘dbfield4′,
      ‘dbfield5′,
      …
      ‘dbfieldn’,
    );
    require("sites/all/libraries/PHPExcel/PHPExcel/IOFactory.php");
    if(($handle = fopen ( $file->filepath, "r" )) !== FALSE) {
      $PHPExcel = new PHPExcel ();
      $PHPReader = new PHPExcel_Reader_Excel2007 ();
      if (! $PHPReader->canRead ( $file->filepath )) {
        $PHPReader = new PHPExcel_Reader_Excel5 ();
        if (! $PHPReader->canRead ( $file->filepath )) {
          echo ‘no Excel’;
          return;
        }
      }
      $PHPExcel = $PHPReader->load ( $file->filepath );
      $currentSheet = $PHPExcel->getSheet ( 0 );
      /**取得一共有多少列*/
      $allColumn = $currentSheet->getHighestColumn();
      //取得共有多少列,若不使用此靜態方法,獲得的$col是檔案列的最大的英文大寫字母
      $col = PHPExcel_Cell::columnIndexFromString($currentSheet->getHighestColumn());
      /**取得一共有多少行*/
      $allRow = $currentSheet->getHighestRow();
      //迴圈讀取每個儲存格的內容。注意行從1開始,列從A開始
      for($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) {
        $token_db = $row_db = $field = array();
        $i = 0;
        $query = ”;
        for($colIndex = 0; $colIndex <= $col; $colIndex++) {
          //$addr = $colIndex.$rowIndex;
          //$cell = $currentSheet->getCell($addr)->getValue();
          $cell = $currentSheet->getCellByColumnAndRow($colIndex, $rowIndex)->getValue();
          $cell = trim($cell);
          if($cell instanceof PHPExcel_RichText) {
            //富文本轉換字串
            $cell = $cell->__toString();
          }
          if ($colIndex == ‘A’ && !intval($cell)) {
            $paseRows++;
            break;
          }
          $field[] = $table[$i];
          $token_db[] = "’%s’";
          $row_db[] = $cell;
          $query .= $table[$i]." = ‘%s’, ";
          $i++;
        }
        $row++;
        if ($row_db) {
          db_query(‘INSERT INTO {db_import} (‘. implode(‘, ‘, $field) .’, created) VALUES(‘. implode(‘, ‘, $token_db) .’, %d)’, array_merge($row_db, array($timestamp)));
          $insertRows++;
        }
      }
      fclose ( $handle );
    }
    drupal_set_message(t(‘檔案 @file 匯入成功.’, array(‘@file’ => $file->filename)));
    drupal_set_message("解析".$row."條資料完畢,新增共".$insertRows."條資料,沒有試題類型ID的".$paseRows."條資料。");
  }
  else {
    drupal_set_message(t(‘File to import not found.’), ‘error’);
    $form_state['redirect'] = ‘admin/content/db/import’;
    return;
  }
}
?>

上面代碼部分注意一下幾點:

 代碼如下 複製代碼


$allColumn = $currentSheet->getHighestColumn();

 擷取的列為英文大寫字母的數組索引。

 代碼如下 複製代碼

$col = PHPExcel_Cell::columnIndexFromString($currentSheet->getHighestColumn());

將英文大寫字母索引格式化為數字,索引值從0開始計算。
本代碼支援讀取Excel 2007 及之前的格式。

聯繫我們

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