本文介绍了使用PHPExcel循环工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHPExcel库来读取Excel文件并对其执行处理。我想遍历每个工作表。我检查了文档,所有我能找到更改活动工作表索引或只加载指定的工作表。



这里是文档的循环示例,以供参考:

 <?php 
$ objReader = PHPExcel_IOFactory :: createReader('Excel2007');
$ objReader-> setReadDataOnly(true);

$ objPHPExcel = $ objReader-> load(test.xlsx);
$ objWorksheet = $ objPHPExcel-> getActiveSheet();

echo'< table>'。 \\\
;
foreach($ objWorksheet-> getRowIterator()as $ row){
echo'< tr>'。 \\\
;

$ cellIterator = $ row-> getCellIterator();
$ cellIterator-> setIterateOnlyExistingCells(false); //循环所有的单元格,
//即使没有设置。
//默认情况下,只有被设置的单元格
//将被
//迭代。
foreach($ cellIterator as $ cell){
echo'< td>'。 $ cell-> getValue()。 '< / td>'。 \\\
;
}

echo'< / tr>'。 \\\
;
}
echo'< / table>'。 \\\
;
?>


解决方案

您正在使用迭代器。你看了/ Tests目录中迭代器的代码示例吗?如果是这样,您可能已经看到了WorksheetIterator的引用。另外,PHPExcel对象的getAllSheets()方法返回一个工作表数组,它允许您使用一个foreach循环


I'm using the PHPExcel library to read an Excel file and perform processing on it. I want to loop through each worksheet. I checked the documentation and all I could find was changing the active worksheet index or only loading specified worksheets. How can I loop through all worksheets?

Thank you for any help.

Here is the documentation's looping example, for reference:

<?php
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);

$objPHPExcel = $objReader->load("test.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();

echo '<table>' . "\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";
?>
解决方案

You're using iterators. Did you look at the code example for iterators in the /Tests directory? If so, you might have seen reference to the WorksheetIterator

Alternatively, the getAllSheets() method of the PHPExcel object returns an array of worksheets, which allows you to use a foreach loop

这篇关于使用PHPExcel循环工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 23:17