如何使用 PHPExcel 读取 xlsx 文件的第二页?

发布于 2024-10-01 22:50:17 字数 998 浏览 2 评论 0原文

我知道如何阅读我的 xlsx 电子表格并循环浏览第一张表格。

它有 5 张,除了第一张之外,我很难找到其他任何一张。

这是我正在使用的代码,直接来自文档。 您可以看到我尝试使用 setActiveSheet,但这引发了错误调用未定义的方法 PHPExcel::setActiveSheet()

代码

$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("cmt_school_data.xlsx");
//$objPHPExcel->setActiveSheet(1);
$objWorksheet = $objPHPExcel->getActiveSheet();

echo '<table border=1>' . "\n";

foreach ($objWorksheet->getRowIterator() as $row) {

  echo '<tr>' . "\n";

  $cellIterator = $row->getCellIterator();

  // This loops all cells, even if it is not set.
  // By default, only cells that are set will be iterated.
  $cellIterator->setIterateOnlyExistingCells(false);

  foreach ($cellIterator as $cell) {
    echo '<td>' . $cell->getValue() . '</td>' . "\n";
  }

  echo '</tr>' . "\n";

}

echo '</table>' . "\n";

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 the code I am using which was straight from the documentation.
You can see I tried to utilize setActiveSheet, but that threw the error Call to undefined method PHPExcel::setActiveSheet().

Code:

$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("cmt_school_data.xlsx");
//$objPHPExcel->setActiveSheet(1);
$objWorksheet = $objPHPExcel->getActiveSheet();

echo '<table border=1>' . "\n";

foreach ($objWorksheet->getRowIterator() as $row) {

  echo '<tr>' . "\n";

  $cellIterator = $row->getCellIterator();

  // This loops all cells, even if it is not set.
  // By default, only cells that are set will be iterated.
  $cellIterator->setIterateOnlyExistingCells(false);

  foreach ($cellIterator as $cell) {
    echo '<td>' . $cell->getValue() . '</td>' . "\n";
  }

  echo '</tr>' . "\n";

}

echo '</table>' . "\n";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

柒七 2024-10-08 22:50:17

好吧……这些名字都是骗人的。 setActiveSheetIndex 也执行 get 操作,所以解决方案是这样的

$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("cmt_school_data.xlsx");
$objWorksheet = $objPHPExcel->setActiveSheetIndex(1);
//objWorksheet = $objPHPExcel->getActiveSheet();
echo '<table border=1>' . "\n";
foreach ($objWorksheet->getRowIterator() as $row) {
  echo '<tr>' . "\n";
  $cellIterator = $row->getCellIterator();
  $cellIterator->setIterateOnlyExistingCells(false); // This loops all cells,
                                                     // even if it is not set.
                                                     // By default, only cells
                                                     // that are set will be
                                                     // iterated.
  foreach ($cellIterator as $cell) {
    echo '<td>' . $cell->getValue() . '</td>' . "\n";
  }
  echo '</tr>' . "\n";
}
echo '</table>' . "\n";

Ok...the names are deceiving. setActiveSheetIndex also does a get so the solution was this

$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("cmt_school_data.xlsx");
$objWorksheet = $objPHPExcel->setActiveSheetIndex(1);
//objWorksheet = $objPHPExcel->getActiveSheet();
echo '<table border=1>' . "\n";
foreach ($objWorksheet->getRowIterator() as $row) {
  echo '<tr>' . "\n";
  $cellIterator = $row->getCellIterator();
  $cellIterator->setIterateOnlyExistingCells(false); // This loops all cells,
                                                     // even if it is not set.
                                                     // By default, only cells
                                                     // that are set will be
                                                     // iterated.
  foreach ($cellIterator as $cell) {
    echo '<td>' . $cell->getValue() . '</td>' . "\n";
  }
  echo '</tr>' . "\n";
}
echo '</table>' . "\n";
╰ゝ天使的微笑 2024-10-08 22:50:17
<?php

/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../../../Classes/');

/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';


$inputFileType = 'Excel5';
//  $inputFileType = 'Excel2007';
//  $inputFileType = 'Excel2003XML';
//  $inputFileType = 'OOCalc';
//  $inputFileType = 'Gnumeric';
$inputFileName = './sampleData/example1.xls';

echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
echo 'Loading all WorkSheets<br />';
$objReader->setLoadAllSheets();
$objPHPExcel = $objReader->load($inputFileName);


echo '<hr />';

echo $objPHPExcel->getSheetCount(),' worksheet',(($objPHPExcel->getSheetCount() == 1) ? '' : 's'),' loaded<br /><br />';
$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    echo **$sheetIndex**,' -> ',$loadedSheetName,'<br />';
    $sheetData = $objPHPExcel->**getSheet**(**$sheetIndex**)->toArray(null,true,true,true);
    var_dump($sheetData);

}?>
<?php

/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../../../Classes/');

/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';


$inputFileType = 'Excel5';
//  $inputFileType = 'Excel2007';
//  $inputFileType = 'Excel2003XML';
//  $inputFileType = 'OOCalc';
//  $inputFileType = 'Gnumeric';
$inputFileName = './sampleData/example1.xls';

echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
echo 'Loading all WorkSheets<br />';
$objReader->setLoadAllSheets();
$objPHPExcel = $objReader->load($inputFileName);


echo '<hr />';

echo $objPHPExcel->getSheetCount(),' worksheet',(($objPHPExcel->getSheetCount() == 1) ? '' : 's'),' loaded<br /><br />';
$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    echo **$sheetIndex**,' -> ',$loadedSheetName,'<br />';
    $sheetData = $objPHPExcel->**getSheet**(**$sheetIndex**)->toArray(null,true,true,true);
    var_dump($sheetData);

}?>
不如归去 2024-10-08 22:50:17

我知道现在回答已经太晚了。但我找到解决方案如下。

//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();

然后,要通过索引访问工作表,请使用 getSheet() 方法。请注意,工作表的索引从 0 开始。
例如

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

,在您的情况下,如果您只想读取 Sheet-2,

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

或者从 Excel 文件中读取所有工作表,则必须使用 foreach 循环,如下所示。

    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 "<pre>";
    echo count($finaldata);
    print_r($finaldata);
    die();*/

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 "<pre>";
    echo count($finaldata);
    print_r($finaldata);
    die();*/
极致的悲 2024-10-08 22:50:17

如何使用 PHPExcel 读取单个 Excel 文件中的多个工作表。 [ 使用 Codeigniter 3.1.11 ]

来自单个 excel 文件的多个工作表
1https://i.sstatic.net/KyPQz.png

源代码
// 批量上传
函数批量上传()
{
$输出=数组();

    $file_upload    = $_FILES['bulk_karvy_file']['tmp_name'];

    if (isset($file_upload) && !empty($file_upload)){ 

        //You can add directly the Composer Autoloder in your controller: 
        require FCPATH . 'vendor/autoload.php';

        try{   
            $db_spreadsheet = PHPExcel_IOFactory::load($file_upload);   
        }   
        catch (Exception $e){
            die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.@$e->getMessage()); 
        }   

        // sheet list
        $sheetListArray = ["Ann B","Ann C","Ann E","Ann F"];

        $sheetData = [];
        
        $sheetCount = $db_spreadsheet->getSheetCount(); 

        if(is_null($sheetCount))
        {}
        else{

            // Read Excel Sheet
            for ($i = 0; $i < $sheetCount; $i++) 
            {
                $sheet  = $db_spreadsheet->getSheet($i);
                $sheetN = $sheet->getTitle();

                if(in_array($sheetN,$sheetListArray))
                {
                    $sheetData[] = array(
                        'data'    => $sheet->toArray(null, true, true, true),
                        'file'    => $sheetN,
                        'total'   => count($sheet->toArray(null, true, true, true))
                    );
             
                }

            
            }

            // Read all Sheets from your Excel file, you have to use foreach loop
            foreach($sheetData as $val)
            {
                $N = @$val['total'];      

                for($i=2; $row <= $N; $i++)
                {
                        $db_ch= 64;
                        $sl_no          = trim($val['data'][$i][chr(++$db_ch)]);
                        if(empty($sl_no)){break;}
                        $ref_no         = trim($val['data'][$i][chr(++$db_ch)]);
                        $remark         = trim($val['data'][$i][chr(++$db_ch)]);
                        $dep_slip_no    = trim($val['data'][$i][chr(++$db_ch)]);
                        $inst_no        = str_pad(trim($val['data'][$i][chr(++$db_ch)]),6, '0', STR_PAD_LEFT);
                        $amount         = trim($val['data'][$i][chr(++$db_ch)]);
                        $drawee_name    = trim($val['data'][$i][chr(++$db_ch)]);
                        $sch_code       = str_pad(trim($val['data'][$i][chr(++$db_ch)]),3, '0', STR_PAD_LEFT);
                        $ufc_code       = trim($val['data'][$i][chr(++$db_ch)]);
                        $acc_no         = trim($val['data'][$i][chr(++$db_ch)]);
                        $ihno           = trim($val['data'][$i][chr(++$db_ch)]);
                        $trno           = trim($val['data'][$i][chr(++$db_ch)]);
                        $tr_dt          = str_replace('/', '-',trim($val['data'][$i][chr(++$db_ch)]));
                        $value_date     = str_replace('/', '-',trim($val['data'][$i][chr(++$db_ch)]));
                        $branch         = trim($val['data'][$i][chr(++$db_ch)]);
                        $file_name      = trim($val['data'][$i][chr(++$db_ch)]);
                        $category       = trim($val['data'][$i][chr(++$db_ch)]);
                        $upload_type    = trim($val['data'][$i][chr(++$db_ch)]);
                        $fl_name        = @$val['file'];
                        $fl_name_id     = @$db_fn->id;
                        $created_at     = date("Y-m-d H:i:s");
                        $updated_at     = date("Y-m-d H:i:s");   [chr(++$db_ch)]);
                }
            }

        } // end of else

        

        
    }

    echo json_encode($sheetData);
}

How do I read multiple worksheet from a single excel file using PHPExcel. [ using Codeigniter 3.1.11 ]

multiple worksheet from a single excel file
1: https://i.sstatic.net/KyPQz.png

Source Code
// Bulk upload
function bulk_upload()
{
$output = array();

    $file_upload    = $_FILES['bulk_karvy_file']['tmp_name'];

    if (isset($file_upload) && !empty($file_upload)){ 

        //You can add directly the Composer Autoloder in your controller: 
        require FCPATH . 'vendor/autoload.php';

        try{   
            $db_spreadsheet = PHPExcel_IOFactory::load($file_upload);   
        }   
        catch (Exception $e){
            die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.@$e->getMessage()); 
        }   

        // sheet list
        $sheetListArray = ["Ann B","Ann C","Ann E","Ann F"];

        $sheetData = [];
        
        $sheetCount = $db_spreadsheet->getSheetCount(); 

        if(is_null($sheetCount))
        {}
        else{

            // Read Excel Sheet
            for ($i = 0; $i < $sheetCount; $i++) 
            {
                $sheet  = $db_spreadsheet->getSheet($i);
                $sheetN = $sheet->getTitle();

                if(in_array($sheetN,$sheetListArray))
                {
                    $sheetData[] = array(
                        'data'    => $sheet->toArray(null, true, true, true),
                        'file'    => $sheetN,
                        'total'   => count($sheet->toArray(null, true, true, true))
                    );
             
                }

            
            }

            // Read all Sheets from your Excel file, you have to use foreach loop
            foreach($sheetData as $val)
            {
                $N = @$val['total'];      

                for($i=2; $row <= $N; $i++)
                {
                        $db_ch= 64;
                        $sl_no          = trim($val['data'][$i][chr(++$db_ch)]);
                        if(empty($sl_no)){break;}
                        $ref_no         = trim($val['data'][$i][chr(++$db_ch)]);
                        $remark         = trim($val['data'][$i][chr(++$db_ch)]);
                        $dep_slip_no    = trim($val['data'][$i][chr(++$db_ch)]);
                        $inst_no        = str_pad(trim($val['data'][$i][chr(++$db_ch)]),6, '0', STR_PAD_LEFT);
                        $amount         = trim($val['data'][$i][chr(++$db_ch)]);
                        $drawee_name    = trim($val['data'][$i][chr(++$db_ch)]);
                        $sch_code       = str_pad(trim($val['data'][$i][chr(++$db_ch)]),3, '0', STR_PAD_LEFT);
                        $ufc_code       = trim($val['data'][$i][chr(++$db_ch)]);
                        $acc_no         = trim($val['data'][$i][chr(++$db_ch)]);
                        $ihno           = trim($val['data'][$i][chr(++$db_ch)]);
                        $trno           = trim($val['data'][$i][chr(++$db_ch)]);
                        $tr_dt          = str_replace('/', '-',trim($val['data'][$i][chr(++$db_ch)]));
                        $value_date     = str_replace('/', '-',trim($val['data'][$i][chr(++$db_ch)]));
                        $branch         = trim($val['data'][$i][chr(++$db_ch)]);
                        $file_name      = trim($val['data'][$i][chr(++$db_ch)]);
                        $category       = trim($val['data'][$i][chr(++$db_ch)]);
                        $upload_type    = trim($val['data'][$i][chr(++$db_ch)]);
                        $fl_name        = @$val['file'];
                        $fl_name_id     = @$db_fn->id;
                        $created_at     = date("Y-m-d H:i:s");
                        $updated_at     = date("Y-m-d H:i:s");   [chr(++$db_ch)]);
                }
            }

        } // end of else

        

        
    }

    echo json_encode($sheetData);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文