Omerimuni
Omerimuni

Reputation: 65

PHPExcel problem with importing 2 .csv to separate sheets

Mission: I need add 2 .csv files to separate sheets Problem: Second import removes second created sheet and puts information on first sheet

$inputFileType = 'CSV'; 
$objReader = PHPExcel_IOFactory::createReader($inputFileType); 
$objReader->setDelimiter(';'); 
$objPHPExcel = $objReader->load('fail1.csv');     
$objPHPExcel->getActiveSheet()->setTitle('laoseis'); 


//teine leht 
$objPHPExcel->createSheet(); 
$objPHPExcel->setActiveSheetIndex(1);     

$objReader = PHPExcel_IOFactory::createReader($inputFileType); 
$objReader->setDelimiter(';'); 
$objPHPExcel->setActiveSheetIndex(1); 
$objPHPExcel = $objReader->load('fail2.csv'); 

$date = new DateTime($_GET['startDate']); 
$objPHPExcel->getActiveSheet()->setTitle('Müük W'.$date->format("W").''); 

How can I solve this problem?

Upvotes: 0

Views: 146

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

PHPExcel doesn't load the second file to your current sheet in an existing PHPExcel object, it creates a new PHPExcel object and loads the file to that, so you're replacing the first completely when you try to load the second.

Load each csv to a separate PHPExcel instance, then copy the worksheet from the second instance to the first.

$objReader1 = PHPExcel_IOFactory::createReader($inputFileType); 
$objPHPExcel1 = $objReader1->load('fail1.csv');     

$objReader2 = PHPExcel_IOFactory::createReader($inputFileType); 
$objPHPExcel2 = $objReader2->load('fail2.csv');

$objPHPExcel2->getActiveSheet()->setTitle('Worksheet 2');
$objPHPExcel1->addExternalSheet($objPHPExcel2->getActiveSheet());

Now $objPHPExcel1 has both worksheets, and you can save that

Upvotes: 2

Related Questions