PHPexcel 将excel表格数据导入数据库

 根据以下代码执行,肯定不会出错。。

// index.php
<form name="frm1" enctype="multipart/form-data" action="insertdb.php" method="post">
   <input name="filename" type="file" /><input name="submit" type="submit" value="import" />
</form>

//insertdb.php

<?php
header("Content-type:text/html;charset:utf-8");
//全局变量
$succ_result=0;
$error_result=0;
@$file=$_FILES['filename'];
$max_size="2000000"; //最大文件限制(单位:byte)
$fname=$file['name'];
$ftype=strtolower(substr(strrchr($fname,'.'),1));
 
 //文件格式
 $uploadfile=$file['tmp_name'];

 if($_SERVER['REQUEST_METHOD']=='POST'){
     if(is_uploaded_file($uploadfile)){
          if($file['size']>$max_size){
         echo "Import file is too large";
         exit;
         }
          if($ftype!='xls'){
         echo "Import file type is error";
          exit;  
         }
     }else{
     echo "The file is not empty!";
      exit;
     }
 }
$dsn="mysql:dbname=me;host=127.0.0.1;charset=utf8";
$user="root";
$pwd='root';
$pdo=new PDO($dsn,$user,$pwd);  //连接mysql数据库

//调用phpexcel类库
require_once 'Classes/PHPExcel.php';
require_once 'Classes/PHPExcel/IOFactory.php';
require_once 'Classes/PHPExcel/Reader/Excel5.php';

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

$objPHPExcel = $objReader->load($uploadfile);

$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
  $arr_result=array();
  $strs=array();

for($j=2;$j<=$highestRow;$j++)
 {
    unset($arr_result);
    unset($strs);
 for($k='A';$k<= $highestColumn;$k++)
    {
     //读取单元格
  @$arr_result  .= $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().',';
    }
 $strs=explode(",",$arr_result);
 $sql="insert into goods(id,name,content,decs) values ($strs[0],'$strs[1]','$strs[2]',$strs[3])";
 echo $sql."<br/>";

 $result=$pdo->exec($sql) or die("执行错误");
 
  if($result>0){
        $succ_result+=1;
    }else{
        $error_result+=1;
   }

}

echo "插入成功".$succ_result."条数据!!!<br>";
echo "插入失败".$error_result."条数据!!!";

?>

 

你可能感兴趣的:(数据库,excel表格)