Table of Contents
Drupal 通过Library 调用 PHPExcel
Drupal 读取Excel并导入到数据库
Home php教程 php手册 Drupal读取Excel并导入到数据库

Drupal读取Excel并导入到数据库

Jun 06, 2016 pm 08:09 PM
drupal excel import database read

PHPExcel OpenXML – 使用PHP来读,写和创建电子表格文件 - 电子表格引擎 PHPExcel 是用来操作Office Excel 文档的一个PHP类库,它基于微软的OpenXML标准和PHP语言。可以使用它来读

PHPExcel – OpenXML – 使用PHP来读,写和创建电子表格文件 -  电子表格引擎

phpexcel LOGO PHPExcel 是用来操作Office Excel 文档的一个PHP类库

PHPExcel 是用来操作Office Excel 文档的一个PHP类库,它基于微软的OpenXML标准和PHP语言。可以使用它来读取、写入不同格式的电子表格,如 Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML等等。

项目主页:https://github.com/PHPOffice/PHPExcel

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 内容,写入到数据库,打印导入结果消息。

归纳起来有这样几点:

  • Drupal 读取Excel 多行多列内容,列数从1到n,行数也是1到n。
  • Drupal 根据数据库结构 n 个字段分别用于存放Excel 1到n列,如果Excel 的列数很多,可以把n列值存放在1个字段中。

这里我解决的是Excel n列值存放到MySQL n个字段中(n不是很大)

这就是在Drupal最后提交上传文件后的函数:

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         $token_db = $row_db = $field = array();
        $i = 0;
        $query = ”;
        for($colIndex = 0; $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;
  }
}
?>

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

(...)
Read the rest of Drupal读取Excel并导入到数据库 (12 words)


© lixiphp for LixiPHP, 2013. | Permalink | No comment | Add to del.icio.us
Post tags: drupal, Excel, OpenXML, PHP, PHPExcel, 电子表格

Feed enhanced by Better Feed from Ozh

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to insert excel icons into PPT slides How to insert excel icons into PPT slides Mar 26, 2024 pm 05:40 PM

1. Open the PPT and turn the page to the page where you need to insert the excel icon. Click the Insert tab. 2. Click [Object]. 3. The following dialog box will pop up. 4. Click [Create from file] and click [Browse]. 5. Select the excel table to be inserted. 6. Click OK and the following page will pop up. 7. Check [Show as icon]. 8. Click OK.

How to read excel data in html How to read excel data in html Mar 27, 2024 pm 05:11 PM

How to read excel data in html: 1. Use JavaScript library to read Excel data; 2. Use server-side programming language to read Excel data.

How does Go language implement the addition, deletion, modification and query operations of the database? How does Go language implement the addition, deletion, modification and query operations of the database? Mar 27, 2024 pm 09:39 PM

Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

Detailed method of inserting Excel circular data chart into PPT Detailed method of inserting Excel circular data chart into PPT Mar 26, 2024 pm 04:26 PM

1. Create a new PPT page and insert the Excel ring chart. 2. Delete the redundant data in the table, leaving two rows of data, and set them in percentage form to facilitate parameter setting. 3. Copy the data in column B to other columns according to display needs. From the sample picture of this column, you can see what it looks like when copying 5 columns. Pay attention to why the animation operation does not use dragging cells to copy, but the honest and practical method of copying and pasting. You will experience it when you actually operate it. 4. After copying N pieces, set the orange part to no color, and you are done. Note: 1. Use PPT to make information charts like this, which can be drawn graphically or accurately produced using Excel data. 2. This technique is valid for Excel 2007 and above.

Get data from Excel via HTML: A comprehensive guide Get data from Excel via HTML: A comprehensive guide Apr 09, 2024 am 10:03 AM

How to get Excel data in HTML? Import Excel files: using elements. Parse Excel files: use xlsx library or browser functionality. Get data: Get the worksheet object, including row and column data. Display data: Use HTML elements (such as tables) to display data.

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

An in-depth analysis of how HTML reads the database An in-depth analysis of how HTML reads the database Apr 09, 2024 pm 12:36 PM

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

See all articles