简体   繁体   English

PHPExcel 检查工作表是否存在

[英]PHPExcel Check if sheet exists

I am using phpExcel, and I can't find anything to check if a sheet exists.我正在使用 phpExcel,我找不到任何东西来检查工作表是否存在。 What I would like to accomplish is something like this:我想完成的是这样的:

if(!$excel->sheetExists(1)){
    $excel->createSheet(1);
    $sheet = $excel->setSheet(1);
}
// Do some stuff with the sheet

So.所以。 My question: How can I check if a sheet exists?我的问题:如何检查工作表是否存在?

Edit编辑

Would this work?这行得通吗?

try{
    $sheet = $this->excel->setActiveSheetIndex(1);
}catch(Exception $e){
    $excel->createSheet(1);
    $sheet = $excel->setActiveSheetIndex(1);
}

If you simply want to know whether a sheetexists at index 1, then如果您只想知道索引 1 处是否存在工作表,则

$sheetCount = $excel->getSheetCount();

will return a count of the worksheets.将返回工作表的计数。 As sheets are indexed incrementally from 0, then a sheet at index 1 will only exist if the count is 2 or more.由于工作表是从 0 开始递增索引的,因此只有在计数为 2 或更多时才会存在索引为 1 的工作表。

If you want to know whether a named sheet exists, then如果你想知道一个命名表是否存在,那么

$sheetNames = $excel->getSheetNames();

will return an array of sheet names (indexed by their index position), and you can then test using in_array();将返回一个工作表名称数组(由它们的索引位置索引),然后您可以使用 in_array() 进行测试;

The

$excel->getSheet()

method will throw an exception if the requested sheet (by index) doesn't exist, so wrap it in a try/catch block would be another approach如果请求的工作表(按索引)不存在,方法将抛出异常,因此将其包装在 try/catch 块中将是另一种方法

$excel->getSheetByName()

returns a NULL value if the named worksheet doesn't exist如果指定的工作表不存在,则返回 NULL 值

您可以使用sheetNameExists($pSheetName)方法按名称检查工作表是否存在。

getSheet($sheetNumber)是检查工作表是否存在的方式。

Yes your code will also work:是的,您的代码也可以使用:

try {
        $objWorksheet =  $objPHPExcel->setActiveSheetIndex(1); 
}
catch (Exception $e) {
    echo 'Sheet is not exists!';
}
$sheet=$excel->getSheet(1);
// or you can get sheet by name $sheet=$excel->getSheetByName("Sheet1");
if(!empty($sheet)&&is_object($sheet)){
      //sheet already exist
}else{
      //sheet does not exist. Write your code here!
}

"TO KNOW THE PRESENT ACTIVE SHEET NUMBER(INDEX)" $this->activeSheet->getActiveSheetIndex() “了解当前活动表编号(索引)” $this->activeSheet->getActiveSheetIndex()

NOTE: $loadExcel=PHPExcel_IOFactory::load("excelSheetName.xlsx");注意:$loadExcel=PHPExcel_IOFactory::load("excelSheetName.xlsx"); $this->activeSheet=$loadExcel; $this->activeSheet=$loadExcel;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM