如何将exel表中数据存入到数据库

来源:互联网 发布:hr人力资源软件排名 编辑:程序博客网 时间:2024/04/29 17:03

最近在做一个项目,平台那边有1000多条数据,都存在exel表中,本来也可以在系统里面一条一条录进去,但是这样太慢,那么有什么好的方法,可以把这数据,点几下按钮,就一次性完成呢。本文为原创,如需转载,请著名来源:http://blog.csdn.net/qq_22327455

下面开始详细讲述:

我的做的功能是用户点击上传文件按钮,选定需要的exel文件,然后再选择需要导入的数据表,点击导入,数据就一次性导入。

1. 首先需要下载一个php的exel类包,在百度里输入:phpexcel下载   随便找个下载,下载后会得到一个phpexcel文件夹。

2.写html代码:新建一个视图文件

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh_cn" lang="zh_cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" rel="Stylesheet" href="/public/css/cuspermission/globalset.css" />
<script src='/public/js/cuspermission/globalset.js'></script>
<script src="/public/js/orgTree.js"></script>
</head>
<body>
<div class="content">
    <center>
        <div style="margin-top:50px;" id="scbox">
            <form action="/exel/save_exeldata" method="post" enctype="multipart/form-data" class="form">
                <div style="margin-top:20px;">
                    <span style="font-size:14px;margin-top:55px;">请上传exel文件:</span>
                    <input id="file" type="file" name="exel" value="" />
                </div>
                <div style="margin-top:30px;">
                    <span style="font-size:14px;">请选择数据库表:</span>
                    <input type="radio" name="table" value="user" />&nbsp;用户表&nbsp;&nbsp;&nbsp;&nbsp;
                    <input type="radio" name="table" value="projects" />项目表
                </div>
                <div style="margin-top:30px;">
                    <input type="hidden" name="max_file_size" value="52428800" />
                    <input id="submit_st" type="button" value="开始导入" />
                </div>
            </form>
        </div>
    <center>    
</div>
    </body>
</html>
<script>
    $(function(){
      $("#submit_st").click(function(){
          var file = $("#file").val();
          if(file == ''){
              alert('您还没有选择文件');
              return false;
          }else{
              if(confirm('您确定要导入吗')){
                  $(this).attr('disabled',true); //提交后禁掉提交按钮,防止重复数据   author:http://blog.csdn.net/qq_22327455
                  $("form").submit();
              }else{
                  return false;
              }
          }
      });  
    });
</script>

3.要将exel表数据导入数据库,我们首先需要将exel表的数据转换成一个数组,得到的数组就好办了,接下来就是将数组中数据插入数据库的事了。下面方法为数据转换的方法。

新建change.php文件

<?php
/*

*@author:
*user: 将excel数据转换为数组
* */
include dirname(dirname(__FILE__)).'/phpexcel/PHPExcel.php';//在第一步下载的文件里有个类文件叫:PHPExcel.php,引入他
function format_excel2array($filePath='',$sheet=0){
        if(empty($filePath) or !file_exists($filePath)){die('file not exists');}
        $PHPReader = new PHPExcel_Reader_Excel2007();        //建立reader对象
        if(!$PHPReader->canRead($filePath)){
                $PHPReader = new PHPExcel_Reader_Excel5();
                if(!$PHPReader->canRead($filePath)){
                        echo 'no Excel';
                        return ;
                }
        }
        $PHPExcel = $PHPReader->load($filePath);        //建立excel对象
        $currentSheet = $PHPExcel->getSheet($sheet);        //**读取excel文件中的指定工作表*/
        $allColumn = $currentSheet->getHighestColumn();        //**取得最大的列号*/
        $allRow = $currentSheet->getHighestRow();        //**取得一共有多少行*/
        $data = array();
        for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){        //循环读取每个单元格的内容。注意行从1开始,列从A开始
                for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
                        $addr = $colIndex.$rowIndex;
                        $cell = $currentSheet->getCell($addr)->getValue();
                        if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
                                $cell = $cell->__toString();
                        }
                        $data[$rowIndex][$colIndex] = $cell;
                }
        }
        return $data;
}


4.在控制器exel.php下建立一个处理数据的方法save_exeldata(),在这个方法里面,调用PHPExcel.php文件,进行数据转换,并保持数据。

<?php
/*
@author:火影忍者-宇智波鼬qq_22327455的专栏   http://blog.csdn.net/qq_22327455
@user 将exel表数据存入数据库
 *  */
class Exel{
    public function save_exeldata(){
        //首先将表单提交的文件保持指定位置
        $file = $_FILES['exel'];
        //echo '<pre>';print_r($file);die();
        //1 错误判断
        if($file['error']!=0){
            echo "<script>alert('文件上传错误');location.href='/xxx';</script>";die();
        }
        //2 限制大小
        if($file['size'] > $_POST['max_file_size']){
            echo "<script>alert('上传文件最大限制50兆');location.href='/xxx';</script>";die();
        }
         
        //这里你也可以根据需要做其他判断,比如文件的类型是否为exel文件类型等。
        
        //3.存放文件
        $path = dirname(dirname(dirname(__FILE__))).'/uploadFile/exel_tmp'; //要存放的路径
        if(!file_exists($path)){ //不存在目录则创建之
            mkdir($path,0777);
        }
        $dest = $path.'/'.$file['name']; //目标将要存放的位置
        move_uploaded_file($file['tmp_name'], $dest); //将存在服务器上的临时文件,保持到你制定的位置
        //上面的经过上面的步骤,已经把exel表放到了你指定的位置了。
        //接下来是找到你指定的位置,找到这个文件,然后把这里面的数据都变成数组,
       

       //4.数据转换  并存入数据库
        $path_s = dirname(dirname(__FILE__));
        include $path_s.'/libs/phpexcel/changge.php';
        $exelist = format_excel2array($dest);
        //echo '<pre>';print_r($exelist);die();//打印看下,是不是已经转换为数组了
        unset($exelist['1']);
        if($_POST['table'] == 'personal'){
            $res = $this->exel_personal($exelist);//exel_personal方法为插入数据 具体将数组里的内容插入数据库,我这里就不写了,每个框架有不同的写法,而且数据和数据库也不一样,也没办法写
            unlink($dest); //销毁文件
            $this->exel_tip($res); //exel_tip方法为插入后不管成功,给出提示,并跳转
        }elseif($_POST['table'] == 'projects'){    
            $res = $this->exel_projects($exelist);//同上
            unlink($dest); //同上
            $this->exel_tip($res); //同上
        }else{
           echo "<script>alert('请选择数据表后再开始导入');location.href='/xxx';</script>";die();
        }
    }
}
?>

到这里,功能均已实现。有兴趣的朋友,可以测试玩玩,以后在工作中,可能会碰到要做这样的功能的。当然现在也有一些工具,可以不用通过程序,就可以直接将exel数据导入数据库,但也有这种情况:exel表给的是字符串,而数据表的那个字段是要存一个id,通过这个id,查询另外一张表,获得这个字符串,那么那样工具就没有办法了。所以用程序来现实就更容易控制,包括一些关联数据,都可以通过查询等办法获取,再插入。好了,就写到这里吧,后面还有什么好玩的咚咚,我再出博客了。




0 0
原创粉丝点击