完美结合ThinkPHP+uploadify+upload+PHPExcel实现无刷新导入数据
分类:PHP_Python| 发布:佚名| 查看:290 | 发表时间:2016/1/15
直接给大家贴代码了,代码附有注释,相信大家都能看懂的,有不明白的地方欢迎给我留言。
前端HTML+JQuery 备注Jquery需要1.x版本,不能用2.x版本
1.引入必要文件及上传input
1 | <load file= "__PUBLIC__/js/jquery-1.11.3.min.js" /> |
2 | <load file= "__PUBLIC__/uploadify/jquery.uploadify.min.js" /> |
3 | <load file= "__PUBLIC__/uploadify/uploadify.css" /> |
4 | <input type= "file" class= "" id= "student" name= "student" > |
2.uploadify使用操作
04 | var upload = "{:U(MODULE_NAME.'/Student/upload')}" ; |
07 | var sid = '{:session_id()}' ; |
09 | var daoruUrl = "{:U(MODULE_NAME.'/Student/daoruHandle')}" |
11 | var modal = $( '#my-modal-loading' ); |
13 | $( '#student' ).uploadify({ |
14 | 'swf' : '__PUBLIC__/uploadify/uploadify.swf' , |
16 | 'buttonText' : '选择文件...' , |
19 | 'formData' :{ 'session_id' :sid}, |
20 | 'fileTypeExts' : '*.xls' , |
22 | 'onUploadStart' : function (file) { |
23 | $( '#alert-content' ).html( '正在上传文件' ); |
27 | 'onUploadSuccess' : function (file, data, response){ |
28 | $( '#alert-content' ).html( '正在导入数据' ); |
29 | data = eval( "(" +data+ ")" ); |
33 | data: { 'file' :data.file}, |
34 | success: function (retdata){ |
3、ThinkPHP控制器上传操作:备注需要引入Upload.class.php空间
04 | 'rootPath' => './Uploads/' , |
06 | 'saveName' => array( 'uniqid' , '' ), |
07 | 'exts' => array( 'xls' ), |
09 | 'subName' => array( 'date' , 'Ymd' ), |
11 | $upload = new Upload($config); |
13 | $info = $upload->upload(); |
15 | $ this ->error($upload->getError()); |
17 | $file = $info[ 'Filedata' ][ 'savepath' ].$info[ 'Filedata' ][ 'savename' ]; |
21 | 'file' => './Uploads/' .$file, |
23 | echo json_encode($data); |
4.导入数据进去mysql
02 | function daoruHandle(){ |
04 | $excelData = excel_to_mysql($file); |
05 | foreach($excelData[ 'data' ] as $row){ |
07 | 'xuehao' =>$row[ 'xuehao' ], |
08 | 'xingming' =>$row[ 'xingming' ], |
09 | 'xingbie' =>($row[ 'xingbie' ]== '男' )?1:0, |
10 | 'mima' =>md5($row[ 'mima' ]), |
12 | M( 'student' )->add($data); |
5.PHPExcel读取Excel文件返回数据函数
01 | function excel_to_mysql($file){ |
04 | import( 'Classes.PHPExcel' ,COMMON_PATH, '.php' ); |
06 | $PHPExcel = new PHPExcel(); |
08 | $PHPReader = new PHPExcel_reader_Excel5(); |
10 | if (!$PHPReader->canRead($file)){ |
11 | $PHPReader = new PHPExcel_Reader_Excel2007(); |
12 | if (!$PHPReader->canRead($file)) return array( 'error' =>1); |
15 | $PHPExcel = $PHPReader->load($file); |
17 | $sheetCount = $PHPExcel->getSheetCount(); |
19 | $sheet=$PHPExcel->getSheet(0); |
21 | $column = $sheet->getHighestColumn(); |
23 | $row = $sheet->getHighestRow(); |
25 | for ($i=1;$i<=$row;$i++){ |
28 | 'xuehao' =>$sheet->getCell( 'A' .$i)->getValue(), |
29 | 'xingming' =>$sheet->getCell( 'B' .$i)->getValue(), |
30 | 'xingbie' =>$sheet->getCell( 'C' .$i)->getValue(), |
31 | 'mima' =>$sheet->getCell( 'D' .$i)->getValue(), |
41 | return array( 'error' =>0, 'data' =>$data); |
通过以上代码实现了ThinkPHP+uploadify+upload+PHPExcel 无刷新导入数据,希望对你有所帮助。