Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a mysql database with an excel file using phpspreadsheet

I am trying to populate a mysql database with an excel file using phpspreadsheet library. I am doing it in the following way but I get just the first row. How can I do it for all the rows

  $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($target_file);
  $worksheet = $spreadsheet->getActiveSheet();
  $rows = [];
  $outer = 1;
  foreach ($worksheet->getRowIterator() AS $row) {
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
        $cells = [];
        foreach ($cellIterator as $cell) {
            $cells[] = $cell->getValue();
        }
        $rows[] = $cells;

        while($outer > 1){
          $data = [
            'testTaker' => $cells[1],
            'correctAnswers' => $cells[2],
            'incorrectAnswers' => $cells[3],
          ];


          if($this->testModel->addTest($data)){
              die('it worked');
          } else {
              die('Something went wrong');
          }

        }
        $outer++;
  }
like image 727
Unah Henry Avatar asked Jan 27 '23 21:01

Unah Henry


1 Answers

This is how I am importing a XLSX spreadsheet with phpSpreadSheet into a MySQL database using PDO (modified to fit your criteria).

// read excel spreadsheet
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
if($reader) {
  $reader->setReadDataOnly(true);
  $spreadsheet = $reader->load($target_file);  
  $sheetData = $spreadsheet->getActiveSheet()->toArray();

  foreach($sheetData as $row) {
    // get columns
    $testTaker = isset($row[0]) ? $row[0] : "";
    $correctAnswers = isset($row[1]) ? $row[1] : "";
    $incorrectAnswers = isset($row[2]) ? $row[2] : "";

    // insert item
    $query = "INSERT INTO item(testTaker, correctAnswers, incorrectAnswers) ";
    $query .= "values(?, ?, ?)";
    $prep = $dbh->prepare($query);
    $prep->execute(array($testTaker, $correctAnswers, $incorrectAnswers));
  }
}
like image 147
Scott Avatar answered May 19 '23 14:05

Scott