PHPExcel检查工作表是否存在 [英] PHPExcel Check if sheet exists
问题描述
我正在使用phpExcel,但找不到任何可检查工作表是否存在的东西.我想完成的事情是这样的:
I am using phpExcel, and I can't find anything to check if a sheet exists. 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?
修改
这项工作可以吗?
try{
$sheet = $this->excel->setActiveSheetIndex(1);
}catch(Exception $e){
$excel->createSheet(1);
$sheet = $excel->setActiveSheetIndex(1);
}
推荐答案
如果您只是想知道工作表是否存在于索引1,那么
If you simply want to know whether a sheetexists at index 1, then
$sheetCount = $excel->getSheetCount();
将返回工作表的计数.由于工作表从0开始递增索引,因此只有在计数为2或更大时,索引为1的工作表才会存在.
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.
如果您想知道命名表是否存在,那么
If you want to know whether a named sheet exists, then
$sheetNames = $excel->getSheetNames();
将返回一个工作表名称数组(按其索引位置索引),然后可以使用in_array();
will return an array of sheet names (indexed by their index position), and you can then test using in_array();
The
$excel->getSheet()
如果所请求的表单(按索引)不存在,该方法将引发异常,因此将其包装在try/catch块中将是另一种方法
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
$excel->getSheetByName()
如果命名的工作表不存在,则返回NULL值
returns a NULL value if the named worksheet doesn't exist
这篇关于PHPExcel检查工作表是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!