Reading a XLSX sheet to feed a MySQL table using PHPExcel

前端 未结 2 1569
死守一世寂寞
死守一世寂寞 2020-12-10 02:02

I found the PHPExcel library brilliant to manipulate Excel files with PHP (read, write, and so on).

But nowhere in the documentation is explained how to read

相关标签:
2条回答
  • 2020-12-10 02:12

    Here is the code

    $inputFileName = $upload_path . $filename;
    $objReader = PHPExcel_IOFactory::createReader('Excel2007');
    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($inputFileName);
    $objWorksheet = $objPHPExcel->getActiveSheet();
    
    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $rows = array();
    for ($row = 1; $row <= $highestRow; ++$row) {
      for ($col = 0; $col <= $highestColumnIndex; ++$col) {
        $rows[$col] = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
      }
      mysql_query("INSERT INTO upload (`item_number`,`qty_sold`,`cost_home`) VALUES ($rows[1],$rows[2],$rows[3])");
    }
    
    ?>
    

    I have tried mysql_query("INSERT INTO upload (col1,col2) VALUES ($rows[1],$rows[2])"); as well but didn't work. The table stays empty

    0 讨论(0)
  • 2020-12-10 02:20

    The first for loops through rows, and the second one loops through columns. So, there are plenty of solutions to your "problem".

    You could, for example, populate an array and make an insert statement for each row. As the following :

    $rows = array();
    for ($row = 1; $row <= $highestRow; ++$row) {
      for ($col = 0; $col <= $highestColumnIndex; ++$col) {
        $rows[$col] = mysql_real_espace_string($objWorksheet->getCellByColumnAndRow($col, $row)->getValue());
      }
    
      mysql_query("INSERT INTO your_table (col1,col2) VALUES ($rows[1],$rows[2])");
    }
    

    Obviously, this code can be improved.

    0 讨论(0)
提交回复
热议问题