使用PHPExcel和Codeigniter读取excel文件并写入数据库

我想在excel文件中写入一些信息到我的数据库。 excel文件看起来像这样。

ID123 | subj1 | 50

ID456 | subj2 | 60

ID786 | subj3 | 70

这是触发控制器中的function的function。

<a href="http://localhost/SEP/index.php/con_test/readExcel"> Click me </a> 

这是控制器中的代码。

 public function readExcel(){ $inputFileName = 'C:\wamp\www\SEP\uploads\Format.xlsx'; // Read your Excel workbook try { $inputFileType = PHPExcel_IOFactory::identify($inputFileName); $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($inputFileName); } catch(Exception $e) { die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage()); } // Get worksheet dimensions $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); $highestColumn = $sheet->getHighestColumn(); // Loop through each row of the worksheet in turn for ($row = 1; $row <= $highestRow; $row++){ // Read a row of data into an array $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE); // Insert row data array into your database of choice here $this->mod_test->insertMarks($rowData); } } 

另外我已经包括include '../third_party/PHPExcel/IOFactory.php'; 在控制器的顶部使用这个。

这是我的模型中的代码。

 public function insertMarks($data){ $this->db->insert('marks', $data); return; } 

这是我第一次使用这个。 我没有得到任何错误,值也没有插入到数据库。 请帮我解决一下这个。

从一个调用rangeToArray$rowData )的返回是一个rangeToArray数组,即使是一个单一的行….我想你可能想要将其insertMarks()化到一个数组,然后insertMarks()

 $this->mod_test->insertMarks($rowData[0]); 

尝试这个

 <?php include ("./Classes/PHPExcel/IOFactory.php"); $inputFileName = './marks.xlsx'; // Read your Excel workbook try { $inputFileType = PHPExcel_IOFactory::identify($inputFileName); $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($inputFileName); } catch(Exception $e) { die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage()); } $sheetInsertData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true); //Read excel rows foreach($sheetInsertData as $rec) { //If you want row as a array use $rec $this->mod_test->insertMarks($rec); //Get column values from row array /*foreach($rec as $recm) { echo $recm."<br>"; }*/ } ?>