I need to use PHPSspreadsheet to export an excel file from a Wordpress site.
I have the package installed, and I put their test case into a function, but it isn't doing anything. I have these functions in a custom plugin file. When I put the "use PhpOffice" part into my original function it gve an error, so I understand it has to be outside of the function, but I am still not sure it is in the right spot.
I put the PHPSpreadsheet example into another function so it would run at init, but I am just hacking away here....
<?php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
//I added this function (spreadfunction) to try to have PHPSpreadsheet run at init for header reasons.
add_action('init', 'spreadfunction');
function spreadfunction() {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
}
//Originally, I had the sample code in this function, but no luck there, but I am using this to trigger it and so I can pass data to it ultimately.
function update_attendance_report_function() {
spreadfunction();
exit;
}
add_action( 'admin_post_nopriv_attendance_report', 'update_attendance_report_function' );
add_action( 'admin_post_attendance_report', 'update_attendance_report_function' );
try this code below...
<?php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
if (isset($_POST['export_excel'])) {
ob_clean(); //this point <========================================
$spreadsheet = new Spreadsheet();
$active_sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
ob_flush(); //and this point <==========================================
} ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.