John Davidson

php - PhpSpreadsheet: two table in a sheet and two autofilter

0 comments
Message:


i am using phpspreadsheet. I have two tables in the same spreadsheet and in both tables I would like to add the autofilter, but it takes into account only the last one added.
Example:


//table 1 code
...
...
//autofilter 1
$spreadsheet->getActiveSheet()->setAutoFilter('A1:E1');

//Table 2 code
...
...
//autofilter 2
$spreadsheet->getActiveSheet()->setAutoFilter('G1:K1');

output: autofilter only from G1 to K1, and not from A1 to E1



My Answer:
> Here is an example code snippet that demonstrates how to add two tables with autofilters in the same spreadsheet using PhpSpreadsheet:

php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Create new Spreadsheet object
$spreadsheet = new Spreadsheet();

// Add data to table 1
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setCellValue('A1', 'Header 1');
$sheet1->setCellValue('A2', 'Data 1');
$$sheet1->setCellValue('A3', 'Data 2');

// Set autofilter for table 1
$sheet1->setAutoFilter('A1:A3');

// Add data to table 2
$sheet2 = $spreadsheet->createSheet();
$sheet2->setCellValue('B1', 'Header 2');
$sheet2->setCellValue('B2', 'Data 3');
$sheet2->setCellValue('B3', 'Data 4');

// Set autofilter for table 2
$sheet2->setAutoFilter('B1:B3');

// Save the spreadsheet
$writer = new Xlsx($spreadsheet);
$writer->save('example.xlsx');


In this code snippet, we first create a new Spreadsheet object and add data to two different sheets (table 1 and table 2). We then set the autofilter for each table using the `setAutoFilter` method. Finally, we save the spreadsheet as an Excel file.

This should allow you to have two tables with autofilters in the same spreadsheet using PhpSpreadsheet.

Rate this post

3 of 5 based on 9505 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us