phpexcel excel数据导入到数据库
Posted 小东2008
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了phpexcel excel数据导入到数据库相关的知识,希望对你有一定的参考价值。
最近做项目遇到要把excel表格的数据导入到mysql数据库里面,一直报错:文件不存在或不可读,经过一下午的排错,终于弄好了,不多说了,直接贴代码:
function impUser(){
ini_set(\'memory_limit\',\'1024M\');
if (!empty($_FILES)) {
$config = array(
\'exts\' => array(\'xlsx\',\'xls\'),
\'maxSize\' => 3145728000,
\'rootPath\' =>"./Public/",
\'savePath\' => \'Uploads/\',
\'subName\' => array(\'date\',\'Ymd\'),
);
$upload = new \\Think\\Upload($config);
if (!$info = $upload->upload()) {
$this->error($upload->getError());
}
vendor("phpExcel.PHPExcel");
$file_name=$upload->rootPath.$info[\'photo\'][\'savepath\'].$info[\'photo\'][\'savename\'];
$extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));//判断导入表格后缀格式
if ($extension == \'xlsx\') {
$objReader =\\PHPExcel_IOFactory::createReader(\'Excel2007\');
$objPHPExcel =$objReader->load($file_name, $encode = \'utf-8\');
} else if ($extension == \'xls\'){
$objReader =\\PHPExcel_IOFactory::createReader(\'Excel5\');
$objPHPExcel =$objReader->load($file_name, $encode = \'utf-8\');
}
$sheet =$objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();//取得总行数
$highestColumn =$sheet->getHighestColumn(); //取得总列数
D(\'Expert\')->execute(\'truncate table qw_expert\');
for ($i = 2; $i <= $highestRow; $i++) {
//看这里看这里,前面小写的a是表中的字段名,后面的大写A是excel中位置
$data[\'id\'] =$objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue();
$data[\'name\'] =$objPHPExcel->getActiveSheet()->getCell("B" .$i)->getValue();
$data[\'sex\'] =$objPHPExcel->getActiveSheet()->getCell("C" .$i)->getValue();
$data[\'thumbnail\'] = $objPHPExcel->getActiveSheet()->getCell("D". $i)->getValue();
$data[\'workunit\'] =$objPHPExcel->getActiveSheet()->getCell("E" . $i)->getValue();
$data[\'phone\'] =$objPHPExcel->getActiveSheet()->getCell("F" .$i)->getValue();
$data[\'sex\'] =$objPHPExcel->getActiveSheet()->getCell("G" .$i)->getValue();
$data[\'email\'] = $objPHPExcel->getActiveSheet()->getCell("H". $i)->getValue();
$data[\'research\'] =$objPHPExcel->getActiveSheet()->getCell("I" . $i)->getValue();
$data[\'sort\'] =$objPHPExcel->getActiveSheet()->getCell("J" .$i)->getValue();
$data[\'time\'] =$objPHPExcel->getActiveSheet()->getCell("K" .$i)->getValue();
//看这里看这里,这个位置写数据库中的表名
D(\'Expert\')->add($data);
}
$this->success(\'导入成功!\');
} else {
$this->error("请选择上传的文件");
}
}
说明:1、
2、下载phpexcel
3、要和数据的字段一致。
以上是关于phpexcel excel数据导入到数据库的主要内容,如果未能解决你的问题,请参考以下文章
php phpexcel-phpexcel 导入 excel出现问题,求解答