https://github.com/PHPOffice/PHPExcel
위 사이트로 들어가서
Download ZIP 버튼을 눌러 라이브러리를 다운 받는다.
압축 해제 후, 프로젝트 폴더 안에 원하는 경로에 넣는다.
<?php
require_once "./PHPExcel-1.8/Classes/PHPExcel.php";
//PHPExcel 인스턴스
$objPHPExcel = new PHPExcel();
//Excel sheet Title 설정
$objPHPExcel -> getActiveSheet() -> setTitle("sheet Title");
$objPHPExcel -> setActiveSheetIndex(0)
-> setCellValue("A1", "Index")
-> setCellValue("B1", "Name")
-> setCellValue("C1", "Age");
//볼드체 설정
$objPHPExcel -> getActiveSheet() -> getStyle("A1:C1") -> getFont() -> setBold(true);
//배경색 설정
$objPHPExcel -> getActiveSheet() -> getStyle("A1:C1") -> getFill() -> setFillType(PHPExcel_Style_Fill::FILL_SOLID) -> getStartColor() -> setRGB("CECBCA");
//A, B, C 열 가로 넓이
foreach(range("A", "C") as $column){
$objPHPExcel -> getActiveSheet() -> getColumnDimension($column) -> setWidth(15);
}
$testArray = [
"index" => "1",
"name" => "Lime",
"age" => "26"
];
//array 행이 많을 때 쓰면 좋다
//test 예제여서 한 행만 엑셀 행 삽입
$count = 0;
while($count < count($testArray){
$idx = $testArray[$count]["index"];
$name = $testArray[$count]["name"];
$age = $testArray[$count]["age"];
//셀 병합
//$objPHPExcel -> setActiveSheetIndex(0)
//-> mergeCells(sprintf("A2:A%s", $count + 3))
//-> setCellValue("A2", "cell merge");
//A2, B2, C2 부터 배열 값 삽입
$num = 2 + $count;
$objPHPExcel -> setActiveSheetIndex(0)
-> setCellValue(sprintf("A%s", $num), $idx)
-> setCellValue(sprintf("B%s", $num), $name)
-> setCellValue(sprintf("C%s", $num), $age);
$count++;
}
//가운데 정렬
$objPHPExcel -> getActiveSheet() -> getStyle(sprintf("A1:D%s", count($testArray) + 1)) -> getAlignment() -> setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//파일 이름 설정
$fileDate = date("Ymd", strtotime("now"));
$fileName = $fileDate . "_" . "ExcelFile";
//엑셀 다운 가능하도록 헤더 셋팅, 리다이렉션
header("Content-Type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=".$fileName.".xls");
header("Cache-Control:max-age=0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel5");
$objWriter -> save("php://output");
exit;
?>
코드를 옮겨 적으면서 testArray 등 조금씩 코드를 변경했다.
설마 싶지만.. 오타가 있을지도..?
나 같은 경우는 require_once를 안해줘서 에러가 났었다.
require_once 로 라이브러리 추가를 잊지 말자.
include 로 추가해도 된다.
https://wickedmagic.tistory.com/583
https://baengsu.tistory.com/33
728x90
'PHP' 카테고리의 다른 글
[Laravel/PHP] Scope ? (0) | 2022.12.12 |
---|---|
str_replace / preg_replace (0) | 2022.09.14 |
PHP 구성 (0) | 2022.08.16 |
PHP 디자인 패턴 (0) | 2022.08.15 |
모던 PHP 란? (0) | 2022.08.14 |