整体思路就是将需要导入的excel转换为数组,然后再写入数据库
public function import_excel(){
if($this->request->file()) {
$file = $this->request->file('excel');
if ($file) {
$file_types = explode(".", $_FILES['excel']['name']); // ["name"] => string(25) "excel文件名.xls"
$file_type = $file_types [count($file_types) - 1];//xls后缀
$file_name = $file_types [count($file_types) - 2];//xls去后缀的文件名
/*判别是不是.xls文件,判别是不是excel文件*/
if (strtolower($file_type) != "xls" && strtolower($file_type) != "xlsx") {
echo '不是Excel文件,重新上传';
die;
}
$info = $file->move(ROOT_PATH . 'public' . DS . 'excel');//上传位置
$path = ROOT_PATH . 'public' . DS . 'excel' . DS;
$file_path = $path . $info->getSaveName();//上传后的EXCEL路径
//echo $file_path;//文件路径
//获取上传的excel表格的数据,形成数组
$re = $this->actionRead($file_path, 'utf-8',$file_type);
array_splice($re, 1, 0);
unset($re[0]);
dump($re); //查看数组
exit;
/*将数组的键改为自定义名称*/
$keys = array('jgmc', 'qymc', 'sshy', 'jrcp', 'ffje', 'fkrq', 'dqrq', 'ylv', 'bzfs', 'dkxt', 'dbdw');
foreach ($re as $i => $vals) {
$re[$i] = array_combine($keys, $vals);
}
//遍历数组写入数据库
for ($i = 1; $i < count($re); $i++) {
$data = $re[$i];
$res = db('数据库表名')->insert($data);
}
}
}
return $this->view->fetch();
}
public function actionRead($filename,$encode='utf-8',$file_type){
//这里需要引入PHPexcel,在网上找就行了
require_once EXTEND_PATH . 'phpexcel/Classes/PHPExcel.php';
if($file_type == 'xls'){
$objReader = \PHPExcel_IOFactory::createReader('Excel5');//xls
}else{
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');//xlsx
}
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
//return $highestRow;
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
//var_dump($highestColumnIndex);
$excelData = array();
for($row = 1; $row <= $highestRow; $row++) {
for ($col = 0; $col < $highestColumnIndex; $col++) {
$excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
}
return $excelData;
}