首先是先下载PHPExcel类。 下载地址:https://github.com/PHPOffice/PHPExcel
将类库放到application->libraries中
准备工作做好了, 然后开始进行导入
首先 创建from表单
<?php echo form_open_multipart('welcome/php_excel');?> <input type="file" name="file" size="20" /> <br /><br /> <input type="submit" value="upload" /> </form>
在对应的控制器中,进行文件上传
public function php_excel() { $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'xls'; $config['max_size'] = 100; $config['max_width'] = 1024; $config['max_height'] = 768; $this->load->library('upload', $config); if (!$this->upload->do_upload('file')) { $error = array('error' => $this->upload->display_errors()); $this->load->view('myform', $error); } else { $data = array('upload_data' => $this->upload->data()); $list = $this->import_excel($data['upload_data']['full_path']); //$list就是取出的内容 在这里进行存入数据库等项目需要的逻辑处理 var_dump($list); //$this->load->view('formsuccess', $data); } }
上传文件以后才可以获取文件内容,也就是import_excel这个方法,这个方法返回的是自己拼接的键对值的Excel表中的内容,
在获取到这些内容以后 上传到数据库就不难了
public function import_excel($filename) { $this->load->library("phpexcel");//ci框架中引入excel类 $objPHPExcel = new PHPExcel(); $objReader = \PHPExcel_IOFactory::createReader('Excel5'); $objPHPExcel = $objReader->load($filename,$encode='utf-8'); $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); // 取得总行数 $highestColumn = $sheet->getHighestColumn(); // 取得总列数 for($i=2;$i<$highestRow+1;$i++){ $data[$i]['goods_name'] = $objPHPExcel->getActiveSheet()->getCell('A'.$i)->getValue(); $data[$i]['brand'] = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getValue(); $data[$i]['specification'] = $objPHPExcel->getActiveSheet()->getCell('C'.$i)->getValue(); $data[$i]['store_count'] = $objPHPExcel->getActiveSheet()->getCell('D'.$i)->getValue(); $data[$i]['shop_price'] = $objPHPExcel->getActiveSheet()->getCell('E'.$i)->getValue(); } return $data; }