72 lines
2.4 KiB
PHP
72 lines
2.4 KiB
PHP
<?php
|
|
require_once 'config.php';
|
|
if (file_exists('vendor/autoload.php')) {
|
|
require 'vendor/autoload.php';
|
|
} else {
|
|
die('ไม่พบ Library PhpSpreadsheet');
|
|
}
|
|
|
|
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
|
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
|
|
|
checkLogin();
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['export_data'])) {
|
|
$data = json_decode($_POST['export_data'], true);
|
|
|
|
if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
|
|
die("Invalid data format for export.");
|
|
}
|
|
|
|
$spreadsheet = new Spreadsheet();
|
|
$sheet = $spreadsheet->getActiveSheet();
|
|
|
|
// Write headers dynamically based on data keys
|
|
$colIndex = 1; // 1 = A
|
|
$firstRow = $data[0];
|
|
foreach ($firstRow as $key => $value) {
|
|
$cellCoordinate = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex) . '1';
|
|
$sheet->setCellValue($cellCoordinate, strtoupper($key));
|
|
$sheet->getStyle($cellCoordinate)->getFont()->setBold(true);
|
|
$colIndex++;
|
|
}
|
|
|
|
// Write data rows
|
|
$rowNum = 2;
|
|
foreach ($data as $row) {
|
|
$colIndex = 1;
|
|
foreach ($row as $key => $value) {
|
|
$cellCoordinate = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex) . $rowNum;
|
|
$sheet->setCellValueExplicit($cellCoordinate, $value, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
|
|
$colIndex++;
|
|
}
|
|
$rowNum++;
|
|
}
|
|
|
|
// Auto-size columns
|
|
$maxCol = count($firstRow);
|
|
for ($i = 1; $i <= $maxCol; $i++) {
|
|
$colStr = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($i);
|
|
$sheet->getColumnDimension($colStr)->setAutoSize(true);
|
|
}
|
|
|
|
// Output file
|
|
$fileName = 'HOSxP_Export_' . date('Ymd_His') . '.xlsx';
|
|
if (!empty($_POST['original_filename'])) {
|
|
$original = $_POST['original_filename'];
|
|
$info = pathinfo($original);
|
|
$basename = $info['filename'];
|
|
$fileName = $basename . '_ตรวจสอบแล้ว.xlsx';
|
|
}
|
|
|
|
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
|
header('Content-Disposition: attachment;filename="' . $fileName . '"');
|
|
header('Cache-Control: max-age=0');
|
|
|
|
$writer = new Xlsx($spreadsheet);
|
|
$writer->save('php://output');
|
|
exit;
|
|
} else {
|
|
die("No data to export.");
|
|
}
|