tp3.2.3運用phpexcel將excel文件導入mysql數據庫

1,下載PHPExcel
2,配置將下載好的PHPExcel文件與PHPExcel.php 放到thinkphp 根目錄 include/Library/Org/Util/下面
3,同時將PHPExcel.php 更名爲 PHPExcel.class.php
以上是將PHPexcel擴展添加到tp裏面(本人tp版本爲3.2.3)

4,html代碼
tp標籤
<!-- $Id: brand_list.htm 15898 2009-05-04 07:25:41Z liuhui $ -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>零件管理</title>
<meta name="robots" content="noindex, nofollow">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="__PUBLIC__/css/page.css" rel="stylesheet" type="text/css" />
<link href="__PUBLIC__/styles/general.css" rel="stylesheet" type="text/css" />
<link href="__PUBLIC__/styles/main.css" rel="stylesheet" type="text/css" />
<link href="__PUBLIC__/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="__PUBLIC__/js/jquery.js"></script>
</head>
<body>
<form method="post" action="" name="theForm" id="uploadForm" enctype="multipart/form-data">
      <input type="file" class="se2" name="file" id="file" size="45" onchange="checkField(this.value)" style="height: 30px; width: 300px;"/>
      <label for="f_file">
          <input class="se1" type="button" value="導入" />
      </label>
</form>
</body>
</html>
<script>
function checkField(val)
{
    UpladFile();
    changev();
}
function UpladFile() {
    var fileObj = document.getElementById("file").files[0]; // 獲取文件對象
    var FileController = "__URL__/doleadin";     // 接收上傳文件的後臺地址
    // FormData 對象
    var form = new FormData();
    form.append("author", "hooyes");      // 能夠增長表單數據
    form.append("file", fileObj);       // 文件對象
    // XMLHttpRequest 對象
    var xhr = new XMLHttpRequest();
    xhr.open("post", FileController, true);
    xhr.onload = function () {
        alert('上傳完成!');
    };
    xhr.send(form);
}
function changev(){
    $('#file').attr('value','');
}
</script>

5,tp後臺接受並處理上傳文件代碼
//處理文件上傳 並導入mysql
    public function doleadin()
    {
        $upload = new \Think\Upload();// 實例化上傳類
        $upload->maxSize   =     3145728 ;// 設置附件上傳大小
        $upload->exts      =     array('xls', 'xlsx');// 設置附件上傳類
        $upload->savePath  =      '/'; // 設置附件上傳目錄
        // 上傳文件
        $info   =   $upload->uploadOne($_FILES['file']);
        $filename = './Uploads/'.$info['savepath'].$info['savename'];
        $exts = $info['ext'];

        if(!$info) {// 上傳錯誤提示錯誤信息
              $this->error($upload->getError());
          }else{// 上傳成功
                  $this->import_excel($filename, $exts);
        }
    }

    /**
     * 導入excel文件
     * @param  string $file excel文件路徑
     * @return array        excel文件內容數組
     */
    public function import_excel($filename, $exts='xls')
    {
        //導入PHPExcel類庫,由於PHPExcel沒有用命名空間,只能inport導入
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.IOFactory");
        //建立PHPExcel對象,注意,不能少了\
        $PHPExcel=new \PHPExcel();
        //若是excel文件後綴名爲.xls,導入這個類
        if($exts == 'xls'){
            import("Org.Util.PHPExcel.Reader.Excel5");
            $PHPReader=new \PHPExcel_Reader_Excel5();
        }else if($exts == 'xlsx'){
            import("Org.Util.PHPExcel.Reader.Excel2007");
            $PHPReader=new \PHPExcel_Reader_Excel2007();
        }


        //載入文件
        $PHPExcel=$PHPReader->load($filename);
        //獲取表中的第一個工做表,若是要獲取第二個,把0改成1,依次類推
        $currentSheet=$PHPExcel->getSheet(0);
        //獲取總列數
        $allColumn=$currentSheet->getHighestColumn();
        //獲取總行數
        $allRow=$currentSheet->getHighestRow();
        //循環獲取表中的數據,$currentRow表示當前行,從哪行開始讀取數據,索引值從0開始
       $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;
                }
        }
        if(is_file($filename)){
            unlink($filename);
        }
        $this->save_import($data);
    }

    //保存數據到數據庫
    public function save_import($data)
    {
        //零件配置表
        $obj_dlaccess=new \Model\Dl_accessModel();
        //零件系列表
        $obj_info = new \Model\Dl_infoModel();
        //城市MOdel
        $city_info = new \Model\CityModel();
        $result_msg = array();

        foreach ($data as $k=>$v){
           // $v['C'] = (String)$data[$k]['C'];

            if($k >= 2){
                //$v['C'] = (String)$data[$k]['C'];

                $data = '';
                //系列id
                $info_name = (String)htmlspecialchars(trim($v['B']));
                $info_id = $obj_info->file_exist($info_name);
                if($info_id){
                    $data['info_id'] = $info_id;
                    $data['access_name'] = htmlspecialchars(trim($v['C']));
                    $city_name = htmlspecialchars(trim($v['D']));
                    $data['city_id'] = $city_info->city_id($city_name);
                    $data['access_mark'] = htmlspecialchars(trim($v['E']));
                    $access_num = (int)htmlspecialchars(trim($v['F']));
                    if(is_int($access_num)){
                        $data['access_num'] = $access_num;
                        $access_price = $v['G'];
                        $arr = explode('/',$access_price);
                        if(is_array($arr)){
                               $data['access_price']=$arr[0];
                               if($arr[1]=='元'){
                                   $data['price_stu'] = 1;
                               }else{
                                   $data['price_stu'] = 2;
                               }
                               $data['access_dealer'] = htmlspecialchars(trim($v['H']));
                               $data['access_phone'] = htmlspecialchars(trim($v['I']));

                               $arr1 = htmlspecialchars(trim($v['J']));
                               $arr1 = explode('/',$arr1);
                               if(is_array($arr1)){

                                   $data['inventory']=$arr[0];
                                   if($arr[1]=='個'){
                                       $data['inventory_stu'] = 1;
                                   }else{
                                       $data['inventory_stu'] = 2;
                                   }
                                   //查詢是否已存在該零件
                                   $return = $obj_dlaccess->filed_exsit($data);

                                   if(empty($return)){
                                       $data['up_time'] = time();
                                       $result = $obj_dlaccess->to_add($data);
                                       if($result){
                                           array_push($result_msg,'第'.($k-1).'條導入成功!<br/>');
                                       }
                                   }else{
                                           array_push($result_msg,'第'.($k-1).'條導入失敗!<br/>');
                                   }
                               }

                        }else{
                            return 'excel格式錯誤';
                        }
                    }else{
                        return 'excel格式錯誤';
                    }
                }else{
                    return 'excel格式錯誤';
                }
            }
        }
   // return $result_msg;
    }
注意:如遇到例如:
object(PHPExcel_RichText)[98]
private '_richTextElements' =>
 array
   0 =>
     object(PHPExcel_RichText_TextElement)[99]
       private '_text' => string '96018270' (length=8)
   1 =>
     object(PHPExcel_RichText_Run)[608]
       private '_font' =>
         object(PHPExcel_Style_Font)[164]
           ...
       private '_text' (PHPExcel_RichText_TextElement) => string '/96018290' (length=9)
 此類型的數據  則將該數據 強制轉換爲(string)string字符串便可!
相關文章
相關標籤/搜索