微擎后台导入Excel保存到数据库
微擎后台导入Excel
微擎后台批量导入数据,按照一定格式做好的Excel表格数据导入到数据库。
public function doWebImport(){
global $_W, $_GPC;
$op = $_GPC['op'];
if ($op == 'import') {
$data = $_GPC['students'];
$file = $_FILES['students'];
// var_dump($file);
if (!$file['size']) {
message("文件上传不能为空!");
}
if ($file['name'] && $file['error'] == 0) {
$type = @end(explode('.', $file['name']));
$type = strtolower($type);
if (!in_array($type, array('xls','xlsx'))) {
message('文件格式不正确!','', 'error');
}
set_time_limit(0);
include IA_ROOT .'/framework/library/phpexcel/PHPExcel.php';
include IA_ROOT .'/framework/library/phpexcel/PHPExcel/IOFactory.php';
if ($type == 'xls') {
$inputFileType = 'Excel5';
}else{
$inputFileType = 'Excel2007';
}
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($file['tmp_name']);
$sheet = $objPHPExcel->getSheet(0);
//获取行数与列数
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnNum = PHPExcel_Cell::columnIndexFromString($highestColumn);
$usefullColumnNum = $highestColumnNum;
for($row = 2; $row <= $highestRow;$row++){
$cardno = $sheet->getCellByColumnAndRow(0, $row)->getValue();
$name = $sheet->getCellByColumnAndRow(1, $row)->getValue();
$busid = $sheet->getCellByColumnAndRow(2, $row)->getValue();
$address = $sheet->getCellByColumnAndRow(3, $row)->getValue();
//插入字段
$data = array(
'cardno' => $cardno,
'name' => $name,
'busid' => $busid,
'address' => $address,
'createtime' => time(),
'status' => 1,
);
pdo_insert('student', $data);
}
message('导入成功');
}else{
message('导入失败');
}
}
}