ecxel导入数据也是一个比较常用的功能,他是怎么来实现的呢,下边带你一步步的看
我这里是用的TP的框架
首先需要引入文件,再获取文件名判断文件的类型,然后把表格数据变为数组就可以了,最后就是导入数据了,到此完成。
看代码吧:
public function excel(){
if (request()->isPost()) {
//首先引入文件
Loader::import('PHPExcel.PHPExcel');
Loader::import('PHPExcel.PHPExcel.PHPExcel_IOFactory');
Loader::import('PHPExcel.PHPExcel.PHPExcel_Cell');
//实例化PHPExcel
$objPHPExcel = new PHPExcel();
$file = 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->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'excel');//上传位置
$path = ROOT_PATH . 'public' . DS . 'excel' . DS;
$file_path = $path . $info->getSaveName();//上传后的EXCEL路径
//获取上传的excel表格的数据,形成数组
$re = $this->actionRead($file_path, 'utf-8');
/*file_put_contents('pro.txt', print_r($re,true));die;*/
array_splice($re, 1, 0);
unset($re[0]);
/*将数组的键改为自定义名称*/
$keys = array('tittle', 'one' ,'two','three','four','five','six','type','answer','parent');
foreach ($re as $i => $vals) {
$re[$i] = array_combine($keys, $vals);
}
//遍历数组写入数据库
for ($i = 1; $i < count($re)+1; $i++) {
$data = $re[$i];
$res = db('list')->insert($data);
}
$this->success("导入成功");
}
}
}
public function actionRead($filename, $encode = 'utf-8')
{
//如果是xlsx
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
/*//如果是xls
$objReader = PHPExcel_IOFactory::createReader('Excel5');*/
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$excelData = array();
for($row = 1; $row <= $highestRow; $row++)
{
for ($col = 0; $col < $highestColumnIndex; $col++)
{
$excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
}
return $excelData;
}
此处评论已关闭