thinkphp导入Excel的方法介绍:
开发思路
1、先把Excel文件上传到服务器
2、获取服务器Excel文件内容
3、写入数据库
一、上传Excel文件,使用PHP里自带的上传方法 “\Think\Upload();”,可以很方便的实现。为此我整理下使用这个方法的最简单方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function uploadfile( $fileid , $dir , $maxsize =5242880, $exts = array ( 'gif' , 'jpg' , 'jpeg' , 'bmp' , 'png' ), $maxwidth =430){
$upload = new \Think\Upload();
$upload ->maxSize = $maxsize ;
$upload ->exts = $exts ;
$upload ->rootPath = './uploads/' ;
$upload ->savePath = $dir . '/' ;
$info = $upload ->upload();
if (! $info ) {
return array (status=>0,msg=> $upload ->getError());
} else {
return array (status=>1,msg=> '上传成功' ,filepath=> $info [ $fileid ][ 'savepath' ]. $info [ $fileid ][ 'savename' ]);
}
}
|
这里默认上传到ThinkPHP入口文件index.php所在的文件夹uploads,此方法返回一个数据,状态status=1时为成功,也建议大家在写功能模块时或做封装时,整个系统的在架构初期应该有约定,在必要的情况下返回值用数组形式,成功返回
1 | return array (status=>1,data=>....,info=>.....)
|
失败时可以返回
1 | array (status->0,info=> '可以说明出错的原因' ,....)
|
这样用统一的方式有利于规范开发,团队协作时看代码时可以提高效率,减少思维运转,说远了,上传的方法调用方式如下:
1 2 3 4 5 6 7 8 9 | if (! empty ( $_FILES [ 'xls' ][ 'name' ])){
$upload =uploadfile( 'xls' , 'tempxls' ,5242880, array ( 'xls' , 'xlsx' ));
if ( $upload [ 'status' ]){
$path = $upload [ 'filepath' ];
} else {
$this ->error( $upload [ 'msg' ]);
}
}
|
二、获取Excel数据
1、首先需要引入PHPExcel的类库
1 | require_once 'module/PHPExcel/Classes/PHPExcel/IOFactory.php' ;
|
2、获取Excel第0张表即(Sheet1)
1 2 3 4 | $objPHPExcel = \PHPExcel_IOFactory::load( "uploads/$path" );
$objPHPExcel ->setActiveSheetIndex(0);
$sheet0 = $objPHPExcel ->getSheet(0);
|
3、获取行数,并把数据读取出来$data数组
1 2 3 4 5 6 7 8 9 10 11 | $rowCount = $sheet0 ->getHighestRow();
$data = array ();
for ( $i = 2; $i <= $rowCount ; $i ++){
$item [ 'name' ]= $this ->getExcelValue( $sheet0 , 'A' . $i );
$item [ 'sex' ]= $this ->getExcelValue( $sheet0 , 'B' . $i );
$item [ 'contact' ]= $this ->getExcelValue( $sheet0 , 'C' . $i );
$item [ 'remark' ]= $this ->getExcelValue( $sheet0 , 'D' . $i );
$item [ 'addtime' ]= $this ->getExcelValue( $sheet0 , 'E' . $i );
$data []= $item ;
}
|
三、最后保存到数据
1 2 3 4 5 6 7 8 9 10 11 12 | $success =0;
$error =0;
$sum = count ( $data );
foreach ( $data as $k => $v ){
if (M( 'temp_area3' )->data( $v )->add()){
$success ++;
} else {
$error ++;
}
}
echo "总{$sum}条,成功{$success}条,失败{$error}条。" ;
|
推荐教程:《TP5》
以上就是thinkphp中使用PHPExcel导入Excel的方法的详细内容