I’m using the PHPExcel library to open an existing Excel spreadsheet then create a new worksheet in it.
The code I’m using (excluding all of the initialisation/save etc. as that all works correctly) is as follows:
#======================================================#
# OPEN EXISTING EXCEL SPREADSHEET #
#======================================================#
if (!file_exists( CURRENT_FILE )) {
exit("Please run " . CURRENT_FILE . " first." . EOL);
}
echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$objPHPExcel = PHPExcel_IOFactory::load( CURRENT_FILE );
#======================================================#
#======================================================#
# SET UP WORKSHEETS #
#======================================================#
echo date('H:i:s') , " Create new worksheet for month" , EOL;
$objPHPExcel->createSheet();
$objPHPExcel->getActiveSheet()->setTitle( date("d M", strtotime( $weeks[1] ) ) . ' - ' . date("d M", strtotime( $weeks[4] ) ) );
#======================================================#
What I’m trying to do is:
- Open existing Excel file (which may have 1 or more worksheets in already)
- Create a new worksheet
- Set the new worksheet’s title
- Add content to the new worksheet
However, what seems to be happening is this:
- Opens existing Excel file
- Creates a new worksheet
- Set’s the FIRST worksheet’s title to the date I’ve set up
- Adds content to the FIRST worksheet

So, what I think I need to do is this:
- Open existing Excel file
- Add new worksheet
- Get ID of newly-added worksheet (a command like
mysql_insert_id()) - Set active worksheet to that ID
- Set title of active worksheet
- Add content to active worksheet
However, I can’t seem to find such a command in the PHPExcel documentation. Does one exist? If not, is there any viable workaround to this? I don’t want to overwrite the existing worksheets in this document.
Thanks in advance,
You could take advantage of the fact that the createSheet() method actually returns your new worksheet.