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最后提交上传文件后的函数:
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