我想在codeigniter中将excel文件导入mysql?

Posted

技术标签:

【中文标题】我想在codeigniter中将excel文件导入mysql?【英文标题】:i want to import excel file into mysql in codeigniter? 【发布时间】:2015-11-07 07:47:32 【问题描述】:

我想将excel文件导入mysql。我在db中创建了一个表,表的名称是statement。请指导我

我的控制器

 function my_test()
        
                $table = 'statement';
        $filename ='expense.xls';

      $pathToFile = './uploads/' . $filename;

    //           print_r($pathToFile);die;
               $valuesSql="";
                $this->load->library('Excel_Reader');
                $data = new Excel_Reader($pathToFile);
                $sql = "INSERT INTO $table (";
                for($index = 1;$index <= $data->sheets[0]['numCols']; $index++)
                $sql.= strtolower($data->sheets[0]['cells'][1][$index]) . ", ";
                

                $sql = rtrim($sql, ", ")." ) VALUES ( ";
                for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) 
                $valuesSQL = '';
                for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) 
                $valuesSql .= "\"" . $data->sheets[0]['cells'][$i][$j] . "\", ";
                
                echo $sql . rtrim($valuesSql, ", ")." ) <br>";
                                                           // add this line


                                



    

我的浏览页面是

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?php // echo $error;?>

<?php echo form_open_multipart('Upload_c/my_test');?>

<input type="file" name="file_name" size="20" />

<br /><br />

<input type="submit" name="up" value="upload" />

</form>

</body>
</html>

当我点击视图页面中的上传按钮时,它显示这样的错误

A PHP Error was encountered

Severity: Notice

Message: Undefined offset: 0

Filename: controllers/Upload_c.php

Line Number: 33

A PHP Error was encountered

Severity: Notice

Message: Undefined offset: 0

Filename: controllers/Upload_c.php

Line Number: 38

【问题讨论】:

试试 var_dump($data->sheets) 看看你返回的数据是什么样子的 没有区别我得到同样的错误 这些不是错误。它们是通知,非常类似于您在 PHP 中变量为空时看到的通知。查看“致命错误”之类的内容并将其发布... 将 var_dump 放在抛出通知的代码行之前 【参考方案1】:

试试 PHPEXCEL 而不是 EXCEL_READER...

【讨论】:

【参考方案2】:

请在这个例子中试试这个你不需要任何库它可以在没有任何库的情况下工作--

我的视图文件(index.php)--

<form class="form-horizontal well" action="<?php echo base_url(); ?>index.php/welcome/import" method="post" name="upload_excel" enctype="multipart/form-data">
<input type="file" name="file" id="file" class="input-large">
<button type="submit" id="submit" name="Import" class="btn btn-primary button-loading">Upload</button>
</form>

我的模型(welcome_model.php)--

<?php 
class Welcome_model extends CI_Model
    
        public function insertCSV($data)
            
                $this->db->insert('subject', $data);
                return $this->db->insert_id();
            
    
?>

我的控制器(welcome.php)--

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller 

    public function index()
        
            $this->load->model('welcome_model');
            $this->load->view('index');
        

    public function import()
        
          if(isset($_POST["Import"]))
            
                $filename=$_FILES["file"]["tmp_name"];
                if($_FILES["file"]["size"] > 0)
                  
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     
                            $data = array(
                                'SUBJ_CODE' => $emapData[1],
                                'SUBJ_DESCRIPTION' => $emapData[2],
                                'UNIT' => $emapData[3],
                                'PRE_REQUISITE' => $emapData[4],
                                'COURSE_ID' => $emapData[5],
                                'AY' => $emapData[6],
                                'SEMESTER' => $emapData[7],
                                );
                        $this->load->model('welcome_model');
                        $insertId = $this->welcome_model->insertCSV($data);
                     
                    fclose($file);
                    redirect('welcome/index');
                  
            
        

请试一试,它肯定会工作..

【讨论】:

你应该写 $this->load->model('welcome_model');在循环之外,其余代码看起来不错 CSV 不是 excel 虽然【参考方案3】:
public function dipExcelUpload($file="")
    
        ini_set('MAX_EXECUTION_TIME', -1);
        ini_set('memory_limit', '-1');   

        $file_upload    = $file;

        if (isset($file_upload) && !empty($file_upload)) 

        //You can add directly the Composer Autoloder in your controller: 
        require FCPATH . 'vendor/autoload.php';

        try   
            $objPHPExcel = PHPExcel_IOFactory::load($file_upload);   
           
        catch (Exception $e)
            die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.@$e->getMessage()); 
           
    
        $allDataInSheet         = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);  
        $sheet                  = $objPHPExcel->getSheet(0);  
        $highestRow             = $sheet->getHighestRow();  
        $highestCol             = $sheet->getHighestColumn();  
        $highestco              = $sheet->getHighestDataColumn();  
        $arrayCount             = count($allDataInSheet);   
        $now                    = date("Y-m-d H:i:s");      
        $flag = 0;

        $check_template = array(
            'A' => 'FIN_ID',
            'B' => 'SECCODE',
            'C' => 'SCHEME_NO',
            'D' => 'SEC_SCH',
            'E' => 'DIPNO',
            'F' => 'DIPDT',
            'G' => 'DIPQTY',
            'H' => 'RATE',
            'I' => 'BILLQTY',       
            'J' => 'BILLREF',       
            'K' => 'DUMMY',       
            'L' => 'BILLDT',       
            'M' => 'EORP',       
        );

        $input_template = $allDataInSheet[1];

        array_walk($input_template, $this->trim_value);

        $result = array_diff($check_template, $input_template);

        if(empty($result))
        
            $this->srObject->truncTableDip();

            # loop for inserting data 
            for ($i = 2,$j=0; $i <= $highestRow; $i++)

                $db_ch_ot = 64;

                $fin_id         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $sec_code       = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $sch_no         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $sec_sch        = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $dip_no         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $dip_dt         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);

                if(empty($dip_dt)) 
                    $dip_dt = null;
                else
                    $dip_dt = date("Y-m-d",strtotime($dip_dt));                    
                

                $dip_qty        = trim($allDataInSheet[$i][chr(++$db_ch_ot)]); 
                $rate           = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $bill_qty       = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $bill_ref       = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $dummy          = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $bill_dt        = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);

                if(empty($bill_dt))
                    $bill_dt = null;
                

                $eorp           = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);

                $dt             = date('Y-m-d H:i:s');
                
                $insert_data = array(  
                    "fin_id_data"           => $fin_id,
                    "sec_code_data"         => $sec_code,
                    "sch_no_data"           => $sch_no,
                    "sec_sch_data"          => $sec_sch,
                    "dip_no_data"           => $dip_no,
                    "dip_dt_data"           => $dip_dt,
                    "dip_qty_data"          => $dip_qty,
                    "rate_data"             => $rate,
                    "bill_qty_data"         => $bill_qty,
                    "bill_ref_data"         => $bill_ref,
                    "dummy_data"            => $dummy,
                    "bill_dt_data"          => $bill_dt,
                    "eorp_data"             => $eorp,
                    "created_at_data"       => $dt,
                    "updated_at_data"       => $dt,           
                );
                
                if($this->srObject->insertSdipData($insert_data))
                
                    ++$flag;
                


             //loop close  

            // routine call          
            $this->load->library('mydb');
            $this->mydb->GetMultiResults("CALL ut_sreco_dip_routine()");

          else 
            $this->session->set_flashdata('error', 'Error. Invalid Excel Template');
            redirect(site_url('schill-bill-checking-suuti/sreco'));
           

        $this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
        redirect(site_url('schill-bill-checking-suuti/sreco'));

     
    
 

【讨论】:

以上是关于我想在codeigniter中将excel文件导入mysql?的主要内容,如果未能解决你的问题,请参考以下文章

使用 VBA 从 Access 表中将选定的列导入 Excel

错误超时,在 codeigniter 中使用 excel_reader 上传 excel 文件

在laravel中将Excel导入数据库?

将变量从视图传递到视图 codeigniter

使用 PHP Codeigniter 创建 Excel 文件

如何使用codeigniter将csv文件导入mysql