require("sites/all/libraries/phpexcel/phpexcel/iofactory.php");
<?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;
}
}
?>