How to export multiple worksheets to individual excel files phpexcel

Topics: Developer Forum
Nov 11, 2012 at 12:17 AM

Am trying to export an excel file with 5 worksheets in it.

I would like to export each worksheet as an individual excel file. I have tried using the getWorksheetIterator but no success and it throws this error.

Catchable fatal error: Object of class PHPExcel_Worksheet could not be converted to string in

<!--?php //session_start(); ?-->
<!--?php
 set_time_limit(0);
require_once '../Classes/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader--->setReadDataOnly(false);
//$xlsxfiles=$_SESSION['file'];
//echo $xlsxfiles;
$objPHPExcel = $objReader->load('../upload/Demobook.xlsx');
$num=$objPHPExcel->getSheetCount() ;
$sheetnames=$objPHPExcel->getSheetNames() ;
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
$objWriter->setDelimiter(',');
$objWriter->setEnclosure('');
$objWriter->setLineEnding("\r\n");
$objReader = new PHPExcel_Reader_CSV();
 foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {

    $worksheet->getTitle();



   }
      $objWriter->save("../"."CSV"."/".$worksheet.".".'csv');




//header("Location: column_sort.php");
//exit;





?>

Coordinator
Nov 18, 2012 at 4:22 PM

Your problem is

$objWriter->save("../"."CSV"."/".$worksheet.".".'csv');

You're treating a worksheet object as a string, when it's not a string but a worksheet object. Did you mean

$objWriter->save("../"."CSV"."/".$worksheet->getTitle().".".'csv');

and you also want this inside the foreach loop.

 

You also need to tell the PHPExcel Writer which sheet you wish to save in each iteration using the Writers setSheetIndex() method. Something like:

foreach ($objPHPExcel->getWorksheetIterator() as $idx => $worksheet) {

    $objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
    $objWriter->setDelimiter(',');
    $objWriter->setEnclosure('');
    $objWriter->setLineEnding("\r\n");

    $objWriter->setSheetIndex($idx);
    $objWriter->save("../"."CSV"."/".$worksheet->getTitle().".".'csv');

}