在这个时代从后台导入excel已经是一种时尚了,最近一个系统用到了导入excel文件的需求,小编在网上查询了一下一般都用最牛X的phpexcel。那么小编也是用phpexcel吧!导入excel无非只有两个步骤:
1.上传excel文件。
2.读取excel中的数据到数据库中
那么我们就从第一步开始
上传excel代码:
html部分:
<html>
<head>
<title>上传EXCEL文件</title>
</head>
<body>
<form action="/view/upload/" method="post" enctype="multipart/form-data">
<input name="photo" type="file" value=""/>
<input type="submit" value="上传" name=""/>
</form>
<div>
<ul>
<volist id="vo" name="rs">
<li>{$vo.name}</li>
<li>{$vo.old}</li>
<li>{$vo.sex}</li>
<li>{$vo.sid}</li>
<li>{$vo.guoji}</li>
<li>{$vo.minzu}</li>
<li>{$vo.address}</li>
<li>------------------------------</li>
</volist>
</ul>
</div>
</body>
</html>
执行代码:
<?php
header("Content-type: text/html; charset=utf-8");
// 本类由系统自动生成,仅供测试用途
class IndexAction extends Action {
public function index(){
$list=M("Test");
$rs=$list->select();
$this->assign("rs",$rs);
$this->display();
}
public function upload()
{
import("ORG.Net.UploadFile");
if(!empty($_FILES['photo']['name']))
{
$upload = new UploadFile();
$upload->maxSize = 93145728 ;
$upload->saveRule =time;
$upload->allowExts = array('xls','xlsx');
$upload->savePath = './Uploads/';
if(!$upload->upload())
{
$this->error($upload->getErrorMsg());
}else{
$info = $upload->getUploadFileInfo();
}
import("ORG.Excel.PHPExcel");
$ex=M("test");
$file_name=$info[0]['savepath'].$info[0]['savename'];
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load($file_name,$encode='utf-8');
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
$arrExcel = $objPHPExcel->getSheet(0)->toArray();
for($i=2;$i<=$highestRow;$i++)
{
$data['name']= $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
$data['old']= $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
$data['sex']= $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
$data['sid']= $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
$data['guoji']= $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
$data['minzu']= $objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue();
$data['address'] = $objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
$rs=$ex->add($data);
}
$this->success('Excel数据导入成功','/esoxue.php/Article/index');exit;
}else
{
$this->error("请选择上传的文件");
}
}
}
效果图:
excel数据:
下载phpexcel地址:点击下载
|