循环工作表并清理phpexcel中每个工作表中的列

时间:2012-11-04 10:43:47

标签: loops while-loop phpexcel

尝试循环进入每个工作表并清除任何,在C列中。我得到消息setactive index超出范围请帮忙。我添加了我的代码是否缺少一步。

<?php
include'../Classes/PHPExcel.php';
include'../Classes/PHPExcel/IOFactory.php';

$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load("../upload/combined.xlsx");
ini_set('max_execution_time', 2000);
$i = 0;
while ($objPHPExcel->setActiveSheetIndex($i)){

    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow();

    for($cl=0;$cl<$highestRow+1;$cl++){
        $clean=$objPHPExcel->getActiveSheet()->getCell('C'.$cl)->getValue();
        $cleandone=str_replace(',',"",$clean);
        $objWorksheet->setCellValue('C'.$cl,$cleandone);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('../upload/combined.xlsx');
        $i++;
    }
}
echo "Done";
?>

1 个答案:

答案 0 :(得分:0)

每次单个单元格更改后都不要保存工作簿

不要尝试访问第0行,它不存在...行从1开始

不要在每个单元格之后增加工作表计数器,而是仅在每个单元格之后... ...实际上,为什么不简单地检索工作表计数并在foreach上循环而不是等待你曾尝试过的错误在停止之前访问不存在的工作表:

<?php
include'../Classes/PHPExcel.php';
include'../Classes/PHPExcel/IOFactory.php';

$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load("../upload/combined.xlsx");
ini_set('max_execution_time', 2000);

$worksheetCount = $objPHPExcel->getSheetCount();
for($i=0; $i < $worksheetCount; $i++) {
    $objPHPExcel->setActiveSheetIndex($i);
    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow();

    for($cl=1; $cl<=$highestRow; $cl++) {
        $clean=$objWorksheet->getCell('C'.$cl)->getValue();
        $cleandone=str_replace(',',"",$clean);
        $objWorksheet->setCellValue('C'.$cl,$cleandone);
    }
}

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('../upload/combined.xlsx');

echo "Done";
?>