Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a PHP program that reads an XLS file's worksheets and converts every worksheet to a CSV file.

The error i get:
Fatal error: Uncaught PHPExcel_Exception: You tried to set a sheet active by the out of bounds index: 3. The actual number of sheets is 3. in C:\xampp\htdocs\Technocripa-php\PHPExcel\Classes\PHPExcel.php:695 Stack trace: #0 C:\xampp\htdocs\Technocripa-php\convertCSV.php(34): PHPExcel->setActiveSheetIndex(3) #1 C:\xampp\htdocs\Technocripa-php\convertCSV.php(19): convertXLStoCSV('uploads/Central...', 'Centralizator_f...') #2 {main} thrown in C:\xampp\htdocs\Technocripa-php\PHPExcel\Classes\PHPExcel.php on line 695

Code:

function convertXLStoCSV($infile, $outfile) // the function that converts the file
{
    $fileType = PHPExcel_IOFactory::identify($infile);
    $objReader = PHPExcel_IOFactory::createReader($fileType);

    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($infile);

    //$objPHPExcel->createSheet();

    $i = 0;
    while ($objPHPExcel->setActiveSheetIndex($i)){
        $objWorksheet = $objPHPExcel->getActiveSheet();

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->save($outfile);

        $i++;

        //$sheetNames = $infile->getSheetNames();
    }
}
 ?>


What I have tried:

I have tried placing

$objPHPExcel->createSheet();


outside the loop, but the error persists but just modifies it's data:

Fatal error: Uncaught PHPExcel_Exception: You tried to set a sheet active by the out of bounds index: 4. The actual number of sheets is 4.
Posted
Updated 17-Jun-20 5:46am

The error is very clear, isn't it? You are trying to activate a sheet that does not exist. Remember that indexes are 0 based so trying to access sheet with an index of 3 when there are only 3 sheets will not work. 3 sheets mean there are indexes 0, 1, and 2.
 
Share this answer
 
hello thanks to your question I was able to solve the problem, you really were very close to the solution, it was just putting $ objPHPExcel-> createSheet (); inside the loop
I leave part of my code as an example:

for ($ j = 0; $ j <5; $ j ++) {
        // $ j = 0;

        if ($ j <> 0) {
            $ objPHPExcel-> createSheet ();
        }...
}
 
Share this answer
 
Comments
CHill60 17-Jun-20 12:38pm    
Actually the reason your code doesn't generate the exception has nothing to do with the loop. It's the
if ($ j <> 0) {
that stops the error

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900