Drupal读取Excel并导入数据库实例_PHP教程
Jul 13, 2016 am 10:37 AM
drupal
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 调用 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最后提交上传文件后的函数:
复制代码 代码如下:
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;
}
}
?>
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;
}
}
?>
上面代码部分注意一下几点:
复制代码 代码如下:
$allColumn = $currentSheet->getHighestColumn(); //获取的列为英文大写字母的数组索引。
$col = PHPExcel_Cell::columnIndexFromString($currentSheet->getHighestColumn()); //将英文大写字母索引格式化为数字,索引值从0开始计算。
本代码支持读取Excel 2007 及之前的格式。
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

인기 기사
Repo : 팀원을 부활시키는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
스플릿 소설을이기는 데 얼마나 걸립니까?
3 몇 주 전
By DDD
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
헬로 키티 아일랜드 어드벤처 : 거대한 씨앗을 얻는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌

인기 기사
Repo : 팀원을 부활시키는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
스플릿 소설을이기는 데 얼마나 걸립니까?
3 몇 주 전
By DDD
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
헬로 키티 아일랜드 어드벤처 : 거대한 씨앗을 얻는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제
Gmail 이메일의 로그인 입구는 어디에 있나요?
7288
9


자바 튜토리얼
1622
14


Cakephp 튜토리얼
1342
46


라라벨 튜토리얼
1259
25


PHP 튜토리얼
1206
29

