当前位置:Gxlcms > PHP教程 > phpexcel导入excel到mysql数据库(示例)

phpexcel导入excel到mysql数据库(示例)

时间:2021-07-01 10:21:17 帮助过:19人阅读

2,执行页面insertdb.php

  1. session_start();

  2. header("Content-type:text/html;charset:utf-8");
  3. //全局变量

  4. $succ_result=0;

  5. $error_result=0;
  6. $file=$_FILES['filename'];
  7. $max_size="2000000"; //最大文件限制(单位:byte)
  8. $fname=$file['name'];
  9. $ftype=strtolower(substr(strrchr($fname,'.'),1));
  10. //文件格式
  11. $uploadfile=$file['tmp_name'];
  12. if($_SERVER['REQUEST_METHOD']=='POST'){
  13. if(is_uploaded_file($uploadfile)){
  14. if($file['size']>$max_size){
  15. echo "Import file is too large";
  16. exit;
  17. }
  18. if($ftype!='xls'){
  19. echo "Import file type is error";
  20. exit;
  21. }
  22. }else{
  23. echo "The file is not empty!";
  24. exit;
  25. }
  26. }
  27. require("./conn.php"); //连接mysql数据库

  28. //调用phpexcel类库

  29. require_once 'phpexcel.php';
  30. require_once 'PHPExcel\IOFactory.php';
  31. require_once 'PHPExcel\Reader\Excel5.php';

  32. $objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format

  33. $objPHPExcel = $objReader->load($uploadfile);
  34. $sheet = $objPHPExcel->getSheet(0);
  35. $highestRow = $sheet->getHighestRow(); // 取得总行数
  36. $highestColumn = $sheet->getHighestColumn(); // 取得总列数
  37. $arr_result=array();
  38. $strs=array();

  39. for($j=2;$j<=$highestRow;$j++)

  40. {
  41. unset($arr_result);
  42. unset($strs);
  43. for($k='A';$k<= $highestColumn;$k++)
  44. {
  45. //读取单元格
  46. $arr_result .= $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().',';
  47. }
  48. $strs=explode(",",$arr_result);
  49. $sql="insert into student(typeId,name,sex,age) values ($strs[0],'$strs[1]','$strs[2]',$strs[3])";
  50. echo $sql."
    ";
  51. mysql_query("set names utf8");
  52. $result=mysql_query($sql) or die("执行错误");

  53. $insert_num=mysql_affected_rows();

  54. if($insert_num>0){
  55. $succ_result+=1;
  56. }else{
  57. $error_result+=1;
  58. }
  59. }

  60. echo "插入成功".$succ_result."条数据!!!
    ";

  61. echo "插入失败".$error_result."条数据!!!";
  62. ?>

人气教程排行