PHPSpreadsheet - How do create a extra tab?

Pascal picture Pascal · Feb 17, 2019 · Viewed 7.4k times · Source

I create in my php code a excel file with one tab and give it a name. The code what i use is this.:

// CREATE PHPSPREADSHEET OBJECT
require "../vendor/autoload.php";
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

// CREATE A NEW SPREADSHEET + POPULATE DATA
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Batch');

But how do i create a second tab with another name?

[solved]

// CREATE A NEW SPREADSHEET + POPULATE DATA
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Batch');
// Add some data
$spreadsheet->createSheet();
// Add some data
$spreadsheet->setActiveSheetIndex(1) ->setCellValue('A1', 'world!');
// Rename worksheet
$spreadsheet->getActiveSheet()->setTitle('URL Removed');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$spreadsheet->setActiveSheetIndex(0);

Answer

Bert H picture Bert H · Jul 4, 2019

You can add an extra tab like this:

$spreadsheet->createSheet();
// Zero based, so set the second tab as active sheet
$spreadsheet->setActiveSheetIndex(1)
$spreadsheet->getActiveSheet()->setTitle('Second tab');

If you like, you can read more here.