본문 바로가기

카테고리 없음

php에서 PHPExcel 사용하기

php에서 엑셀 파일을 만들기 위해 사용하는 라이브러리인 PHPExcel에 대해 예제를 통해서 알아보자

<?php
//PHPEXCEL     : https://phpexcel.codeplex.com/
//위에서 다운로드 후, 압축 해제 후, Classes폴더를 라이브러리폴더에 추가 하고 사용 하자 ! 
 
// PHPExcel.php 파일 경로 지정
include_once("ExcelClasses/PHPExcel.php");
 
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();

// Set properties
// Excel 문서 속성
$objPHPExcel->getProperties()
->setCreator("작성자")
->setLastModifiedBy("최종 수정자")
->setTitle("타이틀")
->setSubject("주제")
->setDescription("설명")
->setKeywords("키워드")
->setCategory("라이센스");
 
//엑셀 수정시 비밀번호를 입력해야된다.
$phpexcel->getActiveSheet()->getProtection()->setSheet(true);
$phpexcel->getActiveSheet()->getProtection()->setSort(true);
$phpexcel->getActiveSheet()->getProtection()->setInsertRows(true);
$phpexcel->getActiveSheet()->getProtection()->setFormatCells(true);
$phpexcel->getActiveSheet()->getProtection()->setPassword("0000");             

/*
 * 셀 컨트롤
 */
 
 // 셀 값 입력
 $objPHPExcel->setActiveSheetIndex(0)->setCellValue("A1", "셀값");
 
 // 셀 합치기
 $sheet->mergeCells('A1:C1');
 
 // 셀 가로크기
 $sheet->getColumnDimension('A')->setWidth(6);
 
 // 셀 높이
 $sheet->getRowDimension(1)->setRowHeight(25);
 
 // 셀 숫자형 변환 (1000 -> 1,000)
 $sheet->getStyle('A1:C1')->getNumberFormat()->setFormatCode('#,##0');
 
 // 글꼴 및 정렬
 $sheet->duplicateStyleArray(
 array(
 'font' => array(
 'bold' => true,
 'size' => 14
 ),
 'alignment' => array(
 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
 'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER
 )
 ),
 'A1'
 );
 
 //개별 적용
 $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true); // 셀의 text를 굵게
 $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(13); // 셀의 textsize를 13으로
 
 // 보더 스타일 지정
 $defaultBorder = array(
 'style' => PHPExcel_Style_Border::BORDER_THIN,
 'color' => array('rgb'=>'000000')
 );
 $headBorder = array(
 'borders' => array(
 'bottom' => $defaultBorder,
 'left'   => $defaultBorder,
 'top'    => $defaultBorder,
 'right'  => $defaultBorder
 )
 );
 
 // 다중 셀 보더 스타일 적용
 foreach(range('A','C') as $i => $cell){
 $sheet->getStyle($cell.'1')->applyFromArray( $headBorder );
 }
 
 //줄바꿈 허용
 $phpexcel->getActiveSheet()->getStyle('H4')->getAlignment()->setWrapText(true);
 $phpexcel->getActiveSheet()->getStyle('K6')->getAlignment()->setWrapText(true);
 $phpexcel->getActiveSheet()->getStyle('K8')->getAlignment()->setWrapText(true);
 
 // 배경색 적용
 $sheet->duplicateStyleArray(
 array(
 'fill' => array(
 'type'  => PHPExcel_Style_Fill::FILL_SOLID,
 'color' => array('rgb'=>'F3F3F3')
 )
 ),
 'A1:C1'
 );
 
 // 셀 정렬 (다른방식)
 $sheet->getStyle('A1')
 ->getAlignment()
 ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
 
 $sheet->getStyle('A1:C1')
 ->getAlignment()
 ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 
 //테두리 
 //셀 전체(윤곽선 + 안쪽)
 $objPHPExcel->getActiveSheet()->getStyle('B2:C3')->getBorders()
 ->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
 
 //윤곽선
 $objPHPExcel->getActiveSheet()->getStyle('B5:C6')->getBorders()
 ->getOutline()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
 
 //안쪽
 $objPHPExcel->getActiveSheet()->getStyle('B8:C9')->getBorders()
 ->getInside()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
 
 //세로선
 $objPHPExcel->getActiveSheet()->getStyle('B11:D13')->getBorders()
 ->getVertical()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
 
 //가로선
 $objPHPExcel->getActiveSheet()->getStyle('B15:D17')->getBorders()
 ->getHorizontal()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
 
 
 // Rename sheet
 $sheet->setTitle("주문거래내역");
 
 // 문서 열어볼시 미리 선택되어지는 셀 설정
 $sheet->setSelectedCellByColumnAndRow(0, 1);
 
 // 엑셀 파일 오픈시 활성화될 시트
 $objPHPExcel->setActiveSheetIndex(0);
 
 // 파일의 저장형식이 utf-8일 경우 한글파일 이름은 깨지므로 euc-kr로 변환해준다.
 $filename = iconv("UTF-8", "EUC-KR", "한글 파일명");
 
 // Redirect output to a client’s web browser (Excel5)
 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;
?>

위 예제를 참고하면 대부분 형태의 엑셀파일은 모두 구현이 가능한거 같다.
셀 값 입력, 셀 합치기,가로크기 지정, 세로 높이 지정, 글꼴 및 정렬 등등 대부분의 기능을
포함하고 있으니 참고하여 php에서 엑셀을 만들어 보자

출처 : https://sd23w.tistory.com/406