728x90
php 엑셀다운로드 예시
php 코드에서 엑셀다운로드를 사용 하려면 vendor 에서 설치하고 사용해야 한다.
composer require phpoffice/phpspreadsheet
컴포저에서 설치 후 이용해야 한다.
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
function downloadExcel($filename = 'example.xlsx') {
// 새로운 스프레드시트 객체 생성
$spreadsheet = new Spreadsheet();
// 시트 1 생성
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('첫 번째 시트');
// 헤더 추가
$sheet1->setCellValue('A1', '헤더 1');
$sheet1->setCellValue('B1', '헤더 2');
$sheet1->setCellValue('A2', '데이터 1');
$sheet1->setCellValue('B2', '데이터 2');
// 시트 2 생성
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('두 번째 시트');
// 헤더 추가
$sheet2->setCellValue('A1', '헤더 A');
$sheet2->setCellValue('B1', '헤더 B');
$sheet2->setCellValue('A2', '데이터 A');
$sheet2->setCellValue('B2', '데이터 B');
// 파일 다운로드를 위한 헤더 설정
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;
}
// 함수 호출
downloadExcel('내_엑셀파일.xlsx');
?>
엑셀업로드예시
<?php
$host = 'localhost'; // 데이터베이스 호스트
$db = 'your_database'; // 데이터베이스 이름
$user = 'your_username'; // 사용자 이름
$pass = 'your_password'; // 비밀번호
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
파일 업로드 후 db 에 insert 하는 예시
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
// 파일 업로드 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['excel_file'])) {
$file = $_FILES['excel_file']['tmp_name'];
// 엑셀 파일 읽기
$spreadsheet = IOFactory::load($file);
// 모든 시트 순회
foreach ($spreadsheet->getAllSheets() as $sheet) {
$sheetData = $sheet->toArray();
// 첫 번째 행은 헤더로 가정하고 데이터 삽입
for ($row = 1; $row < count($sheetData); $row++) {
$data = $sheetData[$row];
// 데이터 삽입 쿼리 (여기서 예시로 'your_table'을 사용)
$stmt = $pdo->prepare("INSERT INTO your_table (column1, column2) VALUES (?, ?)");
$stmt->execute([$data[0], $data[1]]);
}
}
echo "데이터가 성공적으로 삽입되었습니다.";
}
?>
<!-- HTML 업로드 폼 -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="excel_file" accept=".xlsx, .xls" required>
<button type="submit">업로드</button>
</form>
728x90
'PHP' 카테고리의 다른 글
php 파일을 pdf 로 다운로드 하는 방법 (0) | 2024.11.23 |
---|---|
음수, 양수 변환 해서 저장하기 (1) | 2024.11.10 |
php TRANSACTION READ UNCOMITTED commit 전 트랜지션 (0) | 2024.09.15 |
php 단방향 암호화 예제 (0) | 2024.07.09 |
tcpdf html 코드 pdf 로 다운로드 하는 방법 php 버전 (0) | 2024.03.27 |