50 lines
1.7 KiB
PHP
Executable File
50 lines
1.7 KiB
PHP
Executable File
<?php
|
|
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
|
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
|
use PhpOffice\PhpSpreadsheet\IOFactory;
|
|
use PhpOffice\PhpSpreadsheet\Reader\Exception as SpreadsheetReaderException;
|
|
|
|
if (!function_exists('generate_excel')) {
|
|
|
|
/*
|
|
This function generates an Excel file using the given headers and data and saves it with the specified filename.
|
|
It utilizes the PhpSpreadsheet library to create and manipulate Excel files.
|
|
|
|
Parameters:
|
|
- $headers: An array containing the column headers for the Excel sheet.
|
|
- $data: An array containing the data to be inserted into the Excel sheet.
|
|
- $filename: The name of the file to be saved.
|
|
- $totals (optional): A flag indicating whether to include total calculations in the Excel sheet.
|
|
*/
|
|
|
|
|
|
function generate_excel($headers, $data, $filename)
|
|
{
|
|
// Create new Spreadsheet object
|
|
$spreadsheet = new Spreadsheet();
|
|
|
|
// Set worksheet title
|
|
$spreadsheet->getActiveSheet()->setTitle('Sheet 1');
|
|
|
|
// Set headers into the spreadsheet
|
|
$spreadsheet->getActiveSheet()->fromArray([$headers], null, 'A1');
|
|
|
|
// Set data into the spreadsheet
|
|
$spreadsheet->getActiveSheet()->fromArray($data, null, 'A2');
|
|
|
|
|
|
|
|
// Create Excel writer
|
|
$writer = new Xlsx($spreadsheet);
|
|
|
|
try {
|
|
// Save Excel file to the specified path
|
|
$writer->save($filename);
|
|
return true; // Return true if file was successfully saved
|
|
} catch (\Exception $e) {
|
|
// Log or handle the exception
|
|
return false; // Return false if there was an error saving the file
|
|
}
|
|
}
|
|
}
|