Home > php教程 > php手册 > body text

Drupal读取Excel并导入到mysql数据库程序代码

WBOY
Release: 2016-05-25 16:37:37
Original
967 people have browsed it

本文章来给大家介绍关于如何在Drupal读取Excel并导入到mysql数据库的方法,这里我们介绍使用excel插件PHPExcel,PHPExcel 是用来操作Office Excel 文档的一个PHP类库,它基于微软的OpenXML标准和PHP语言,可以使用它来读取、写入不同格式的电子表格,如 Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML等等

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(&#39;file&#39;)) {  
        $row = 0; //解析行数  
        $paseRows = 0; //跳过行数 没有值的行  
        $insertRows = 0; //插入行数  
        $table = array(  
          &#39;dbfield1&#39;,  
          &#39;dbfield2&#39;,  
          &#39;dbfield3&#39;,  
          &#39;dbfield4&#39;,  
          &#39;dbfield5&#39;,  
          &hellip;  
          &#39;dbfieldn&#39;,  
        );  
        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 &#39;no Excel&#39;;  
              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 = &#39;&#39;;  
            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 == &#39;A&#39; && !intval($cell)) {  
                $paseRows++;  
                break;  
              }  
              $field[] = $table[$i];  
              $token_db[] = "&#39;%s&#39;";  
              $row_db[] = $cell;  
              $query .= $table[$i]." = &#39;%s&#39;, ";  
              $i++;  
            }  
            $row++;  
            if ($row_db) {  
              db_query(&#39;INSERT INTO {db_import} (&#39;. implode(&#39;, &#39;, $field) .&#39;, created) VALUES(&#39;. implode(&#39;, &#39;, $token_db) .&#39;, %d)&#39;, array_merge($row_db, array($timestamp)));  
              $insertRows++;  
            }  
          }  
          fclose ( $handle );  
        }  
        drupal_set_message(t(&#39;文件 @file 导入成功.&#39;, array(&#39;@file&#39; => $file->filename)));  
        drupal_set_message("解析".$row."条数据完毕,新增共".$insertRows."条数据,没有试题类型ID的".$paseRows."条数据。");  
      }
      else {  
        drupal_set_message(t(&#39;File to import not found.&#39;), &#39;error&#39;);  
        $form_state[&#39;redirect&#39;] = &#39;admin/content/db/import&#39;;  
        return;  
      }  
    } 
?>
Copy after login

上面代码部分注意一下几点,代码如下:

$allColumn = $currentSheet->getHighestColumn();

获取的列为英文大写字母的数组索引,代码如下:

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

将英文大写字母索引格式化为数字,索引值从0开始计算,本代码支持读取Excel 2007 及之前的格式.


教程链接:

随意转载~但请保留教程地址★

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!