How do I read sheet two of an xlsx file with PHPExcel?

前端 未结 3 2100
时光取名叫无心
时光取名叫无心 2020-12-07 21:03

I know how to read my xlsx spreadsheet and loop through the first sheet.

It has 5 sheets and I am having trouble getting to any other than the first.

Here is

3条回答
  •  甜味超标
    2020-12-07 21:59

    I know it's been too late for the answer. But I find solution as below.

    //load library - EXCEL
    $this->load->library('excel');
    $objPHPExcel = PHPExcel_IOFactory::load('./folder/exceldata.xls');
    
    //Get How Many Sheets in your Excel file.
    echo $objPHPExcel->getSheetCount();
    

    Then, to access a sheet by its index, use the getSheet() method. Note that sheets are indexed from 0. e.g.

    //Retrieve the **1st 'tab' worksheet** e.g. called 'Sheet 1'
    $worksheet = $objPHPExcel->getSheet(0);
    

    So in your case, if you want to read only Sheet-2 then,

    $worksheet = $objPHPExcel->getSheet(1);
    

    OR to read all Sheets from your Excel file, you have to use foreach loop as below.

        foreach($objPHPExcel->getWorksheetIterator() as $worksheet)
        {
          $highestRow = $worksheet->getHighestRow();
          $highestColumn = $worksheet->getHighestColumn();
          //echo $highestRow;
          //echo $highestColumn;
          //die();
          for($row=2; $row<=$highestRow; $row++)
          {
            $column1 = $worksheet->getCellByColumnAndRow(0, $row)->getValue();
            $column2= $worksheet->getCellByColumnAndRow(1, $row)->getValue();
    
            $finaldata[] = array(
                'data1'   =>    trim($column1),
                'data2'   =>    trim($column2),
              );
          }
        }
        /*echo "
    ";
        echo count($finaldata);
        print_r($finaldata);
        die();*/
    

提交回复
热议问题