欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Drupal读取Excel并导入数据库实例

程序员文章站 2022-10-12 20:29:16
phpexcel 是用来操作office excel 文档的一个php类库,它基于微软的openxml标准和php语言。可以使用它来读取、写入不同格式的电子表格,如 exc...

phpexcel 是用来操作office excel 文档的一个php类库,它基于微软的openxml标准和php语言。可以使用它来读取、写入不同格式的电子表格,如 excel (biff) .xls, excel 2007 (officeopenxml) .xlsx, csv, libre/openoffice calc .ods, gnumeric, pdf, html等等。

一、drupal 通过library 调用 phpexcel
将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 内容,写入到数据库,打印导入结果消息。
归纳起来有这样几点:
1.drupal 读取excel 多行多列内容,列数从1到n,行数也是1到n。
2.drupal 根据数据库结构 n 个字段分别用于存放excel 1到n列,如果excel 的列数很多,可以把n列值存放在1个字段中。
3.这里我解决的是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 及之前的格式。