- URL 하드코딩 → .env APP_URL 기반 동적 URL로 변경 - DB 연결 하드코딩 → .env 기반으로 변경 - MySQL strict mode DATE 오류 수정
179 lines
7.1 KiB
PHP
179 lines
7.1 KiB
PHP
<?php
|
|
// download_excel.php
|
|
|
|
// 에러 표시 설정 (개발 중에만 사용, 배포 시 비활성화 권장)
|
|
ini_set('display_errors', 0); // 오류를 화면에 출력하지 않음
|
|
ini_set('log_errors', 1);
|
|
ini_set('error_log', '../error_log.txt'); // 에러 로그 파일 경로 설정
|
|
error_reporting(E_ALL);
|
|
|
|
// JSON 응답 헤더 설정
|
|
header('Content-Type: application/json');
|
|
|
|
// JSON 응답을 쉽게 생성하기 위한 함수
|
|
function sendResponse($success, $data = null, $message = '') {
|
|
$response = ['success' => $success];
|
|
if ($data !== null) {
|
|
$response['filename'] = $data;
|
|
}
|
|
if ($message !== '') {
|
|
$response['message'] = $message;
|
|
}
|
|
echo json_encode($response);
|
|
exit;
|
|
}
|
|
|
|
// 사용자 정의 에러 핸들러 설정 (모든 오류를 예외로 변환)
|
|
set_error_handler(function($errno, $errstr, $errfile, $errline) {
|
|
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
|
|
});
|
|
|
|
try {
|
|
// POST 요청인지 확인
|
|
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
|
|
sendResponse(false, null, '잘못된 요청 방법입니다.');
|
|
}
|
|
|
|
// JSON으로 데이터 받기
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
// JSON 디코딩 오류 및 데이터 유무 확인
|
|
if (json_last_error() !== JSON_ERROR_NONE || empty($data)) {
|
|
sendResponse(false, null, '유효하지 않은 데이터 형식이거나 데이터가 없습니다.');
|
|
}
|
|
|
|
// PHPExcel 라이브러리 포함 (경로 확인 필요)
|
|
$phpExcelPath = '../PHPExcel_1.8.0/Classes/PHPExcel.php';
|
|
if (!file_exists($phpExcelPath)) {
|
|
sendResponse(false, null, 'PHPExcel 라이브러리가 존재하지 않습니다. 경로를 확인하세요.');
|
|
}
|
|
require $phpExcelPath;
|
|
|
|
// 새로운 PHPExcel 객체 생성
|
|
$objPHPExcel = new PHPExcel();
|
|
$objPHPExcel->setActiveSheetIndex(0);
|
|
$sheet = $objPHPExcel->getActiveSheet();
|
|
|
|
// 헤더 설정 (14개 컬럼)
|
|
$headers = [
|
|
'번호', '출고일', '현장명',
|
|
'하차업체명', '상차지', '물류업체명',
|
|
'차량톤수', '금 액', '부가세',
|
|
'합계', '착/선불', '차량번호',
|
|
'기사 연락처', '비고'
|
|
];
|
|
$col = 'A';
|
|
foreach ($headers as $header) {
|
|
$sheet->setCellValue($col . '1', $header);
|
|
$col++;
|
|
}
|
|
|
|
// 헤더 행에 음영 처리 추가 (예: 연한 회색 배경)
|
|
$headerRange = 'A1:N1';
|
|
$sheet->getStyle($headerRange)->getFill()->applyFromArray([
|
|
'type' => PHPExcel_Style_Fill::FILL_SOLID,
|
|
'startcolor' => [
|
|
'rgb' => 'D3D3D3' // 연한 회색
|
|
],
|
|
]);
|
|
|
|
// 각 열의 너비 설정 (한글 문자 수 기준)
|
|
$columnWidths = [
|
|
'A' => 10, // 번호
|
|
'B' => 15, // 출고일
|
|
'C' => 30, // 현장명
|
|
'D' => 20, // 하차업체명
|
|
'E' => 20, // 상차지
|
|
'F' => 20, // 물류업체명
|
|
'G' => 15, // 차량톤수
|
|
'H' => 15, // 금 액
|
|
'I' => 15, // 부가세
|
|
'J' => 15, // 합계
|
|
'K' => 10, // 착/선불
|
|
'L' => 20, // 차량번호
|
|
'M' => 20, // 기사 연락처
|
|
'N' => 30, // 비고
|
|
];
|
|
|
|
foreach ($columnWidths as $column => $width) {
|
|
$sheet->getColumnDimension($column)->setWidth($width);
|
|
}
|
|
|
|
// 전체 데이터 범위를 가운데 정렬으로 설정
|
|
$dataRange = 'A1:N' . (count($data) + 1);
|
|
$sheet->getStyle($dataRange)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
|
|
|
|
// 특정 열의 데이터 정렬 설정
|
|
// 전체 데이터를 좌측 정렬로 설정
|
|
$dataRange = 'A2:N' . (count($data) + 1);
|
|
$sheet->getStyle($dataRange)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
|
|
|
|
// 금액 관련 열 (H, I, J)만 우측 정렬로 변경
|
|
$sheet->getStyle('H2:H' . (count($data) + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
|
|
$sheet->getStyle('I2:I' . (count($data) + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
|
|
$sheet->getStyle('J2:J' . (count($data) + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
|
|
|
|
// 데이터 채우기
|
|
$rowNumber = 2;
|
|
foreach ($data as $row) {
|
|
// 각 필드의 존재 여부 확인 및 기본값 설정
|
|
$number = isset($row['번호']) ? $row['번호'] : '';
|
|
$releaseDate = isset($row['출고일']) ? $row['출고일'] : '';
|
|
$workplacename = isset($row['현장명']) ? $row['현장명'] : '';
|
|
$unloadingCompany= isset($row['하차업체명']) ? $row['하차업체명'] : '';
|
|
$loadingPlace = isset($row['상차지']) ? $row['상차지'] : '';
|
|
$logisticsCompany= isset($row['물류업체명']) ? $row['물류업체명'] : '';
|
|
$vehicleTon = isset($row['차량톤수']) ? $row['차량톤수'] : '';
|
|
$amount = isset($row['금 액']) ? $row['금 액'] : '';
|
|
$tax = isset($row['부가세']) ? $row['부가세'] : '';
|
|
$total = isset($row['합계']) ? $row['합계'] : '';
|
|
$paymentMethod = isset($row['착/선불']) ? $row['착/선불'] : '';
|
|
$vehicleNumber = isset($row['차량번호']) ? $row['차량번호'] : '';
|
|
$driverContact = isset($row['기사 연락처']) ? $row['기사 연락처'] : '';
|
|
$remarks = isset($row['비고']) ? $row['비고'] : '';
|
|
|
|
// 데이터 삽입
|
|
$sheet->setCellValue("A{$rowNumber}", $number);
|
|
$sheet->setCellValue("B{$rowNumber}", $releaseDate);
|
|
$sheet->setCellValue("C{$rowNumber}", $workplacename);
|
|
$sheet->setCellValue("D{$rowNumber}", $unloadingCompany);
|
|
$sheet->setCellValue("E{$rowNumber}", $loadingPlace);
|
|
$sheet->setCellValue("F{$rowNumber}", $logisticsCompany);
|
|
$sheet->setCellValue("G{$rowNumber}", $vehicleTon);
|
|
$sheet->setCellValue("H{$rowNumber}", $amount);
|
|
$sheet->setCellValue("I{$rowNumber}", $tax);
|
|
$sheet->setCellValue("J{$rowNumber}", $total);
|
|
$sheet->setCellValue("K{$rowNumber}", $paymentMethod);
|
|
$sheet->setCellValue("L{$rowNumber}", $vehicleNumber);
|
|
$sheet->setCellValue("M{$rowNumber}", $driverContact);
|
|
$sheet->setCellValue("N{$rowNumber}", $remarks);
|
|
|
|
$rowNumber++;
|
|
}
|
|
|
|
// 엑셀 파일 저장 경로 설정
|
|
$filename = 'deliveryfee_' . date('YmdHis') . '.xlsx';
|
|
$filePath = '../excelsave/' . $filename;
|
|
|
|
// PHPExcel Writer 설정
|
|
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
|
|
|
|
// 엑셀 파일 저장
|
|
$objWriter->save($filePath);
|
|
|
|
// 파일이 정상적으로 저장되었는지 확인
|
|
if (file_exists($filePath)) {
|
|
sendResponse(true, $filePath, '');
|
|
} else {
|
|
sendResponse(false, null, '엑셀 파일을 저장하지 못했습니다.');
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
// 에러 로그에 기록
|
|
error_log($e->getMessage());
|
|
|
|
// JSON 응답으로 에러 메시지 전송
|
|
sendResponse(false, null, '엑셀 파일 생성 중 오류가 발생했습니다: ' . $e->getMessage());
|
|
}
|
|
?>
|