Drupal读取Excel并导入到数据库
PHPExcel OpenXML – 使用PHP来读,写和创建电子表格文件 - 电子表格引擎 PHPExcel 是用来操作Office Excel 文档的一个PHP类库,它基于微软的OpenXML标准和PHP语言。可以使用它来读
PHPExcel – OpenXML – 使用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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

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.

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

PHP database connection guide: MySQL: Install the MySQLi extension and create a connection (servername, username, password, dbname). PostgreSQL: Install the PgSQL extension and create a connection (host, dbname, user, password). Oracle: Install the OracleOCI8 extension and create a connection (servername, username, password). Practical case: Obtain MySQL data, PostgreSQL query, OracleOCI8 update record.
