메뉴 건너뛰기

프로그램언어

조회 수 22787 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

 

 

프로그래밍을 하다보면 종종 엑셀 파일을 읽어야 하거나, 생성해야 하는 일이 생긴다.

이를 해결하기 위한 여러 방법이 있지만, 필자는 대체로 PHPExcel을 이용한다.

엑셀을 읽을때 파일을 CSV로 변환하지 않아도 되고, 엑셀 파일을 생성할때도 이상한 경고창을 볼 일도 없기 때문이다.

 

PHPExcel을 사용하기 위해서는 일단 PHP 5.2.0 이상이어야 하고, php_zip, php_xml, php_gd2가 enabled해야 된다.

그리고 소스는 http://phpexcel.codeplex.com/ 에서 다운 받으면 되고, 당연히 여러 형태의 예제 소스로 확인 할 수 있다.

 

PHPExcel을 이용하여 여러가지 형태로 활용 가능하지만 여기서는 가장 기초적인 엑셀 파일 읽기와 생성을 소개하려 한다.

 

우선 엑셀 파일 읽기 예제

<?

require_once "./PHPExcel_1.8.0/Classes/PHPExcel.php"; // PHPExcel.php을 불러와야 하며, 경로는 사용자의 설정에 맞게 수정해야 한다.

$objPHPExcel = new PHPExcel();

require_once "./PHPExcel_1.8.0/Classes/PHPExcel/IOFactory.php"; // IOFactory.php을 불러와야 하며, 경로는 사용자의 설정에 맞게 수정해야 한다.

$filename = './testA.xlsx'; // 읽어들일 엑셀 파일의 경로와 파일명을 지정한다.

try {

  // 업로드 된 엑셀 형식에 맞는 Reader객체를 만든다.

    $objReader = PHPExcel_IOFactory::createReaderForFile($filename);

    // 읽기전용으로 설정

    $objReader->setReadDataOnly(true);

    // 엑셀파일을 읽는다

    $objExcel = $objReader->load($filename);

    // 첫번째 시트를 선택

    $objExcel->setActiveSheetIndex(0);

    $objWorksheet = $objExcel->getActiveSheet();

    $rowIterator = $objWorksheet->getRowIterator();

    foreach ($rowIterator as $row) { // 모든 행에 대해서

               $cellIterator = $row->getCellIterator();

               $cellIterator->setIterateOnlyExistingCells(false); 

    }

    $maxRow = $objWorksheet->getHighestRow();

    for ($i = 0 ; $i <= $maxRow ; $i++) {

               $name = $objWorksheet->getCell('A' . $i)->getValue(); // A열

               $addr1 = $objWorksheet->getCell('B' . $i)->getValue(); // B열

               $addr2 = $objWorksheet->getCell('C' . $i)->getValue(); // C열

               $addr3 = $objWorksheet->getCell('D' . $i)->getValue(); // D열

               $addr4 = $objWorksheet->getCell('E' . $i)->getValue(); // E열

            $reg_date = $objWorksheet->getCell('F' . $i)->getValue(); // F열

               $reg_date = PHPExcel_Style_NumberFormat::toFormattedString($reg_date, 'YYYY-MM-DD'); // 날짜 형태의 셀을 읽을때는 toFormattedString를 사용한다.

      }

 catch (exception $e) {

    echo '엑셀파일을 읽는도중 오류가 발생하였습니다.';

}

?>

 

 

다음은 엑셀 파일 생성 예제

<?

$sql = " SELECT * FROM member_table";

$result = mysql_query($sql);

/** PHPExcel */

require_once "./PHPExcel_1.8.0/Classes/PHPExcel.php"; // PHPExcel.php을 불러와야 하며, 경로는 사용자의 설정에 맞게 수정해야 한다.

$objPHPExcel = new PHPExcel();

// Add some data

for ($i=1; $row=mysql_fetch_array($result); $i++)

{   

   // Add some data

   $objPHPExcel->setActiveSheetIndex(0)

               ->setCellValue("A$i", $row['name'])

               ->setCellValue("B$i", $row['address'])

               ->setCellValue("C$i", $row['phone1'])

               ->setCellValue("D$i", $row['phone2'])

               ->setCellValue("E$i", $row['item'])

               ->setCellValue("F$i",$row['count'])

               ->setCellValue("G$i", $row['req']);

}

// Rename sheet

$objPHPExcel->getActiveSheet()->setTitle('Seet name');

// Set active sheet index to the first sheet, so Excel opens this as the first sheet

$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;

?>

 

읽기 예제 소스는 자신의 프로그래밍 속에 끼워 넣어도 되지만,

쓰기 예제 소스는 header가 존재하기 때문에 header의 위치를 고려하여 프로그래밍 해야 할 것이다.


List of Articles
번호 제목 날짜 조회 수
280 DB 내용을 화면에 출력(이중 for 문) 2015.04.14 21246
279 POST값 통째로 인코딩하기 1 2015.04.06 21175
278 체크박스, post 로 넘기고 받아서 다시 체크하기, checkbox 2017.03.07 21129
277 PHP continue 문 file 2015.04.14 21097
276 FPDF - PHP로 PDF 만들기 2014.02.27 21075
275 RSSReader Class 제작 및 Reader 만들기 file 2016.08.22 21042
274 Ajax로 구연한 실시간 서버시간출력 file 2017.03.06 21031
273 PHP switch 문 file 2015.04.14 20993
272 PHP error 메시지 출력 file 2015.04.14 20924
271 preg_match (정규표현식 매치를 수행합니다) 2016.12.23 20843
270 검색어 처리 루틴 2015.04.14 20778
269 array_slice 배열의 일부를 추출 2016.12.23 20775
268 템플릿 관련 정보 2016.08.22 20732
267 PHP 소스 : 이미지 리사이즈, 섬네일 2014.03.26 20704
266 HTTP Protocol의 data method - GET / POST 2016.04.22 20637
265 [PHP] 한글명 파일 다운로드받기 2014.03.26 20551
264 문자열 치환하기 2015.04.14 20492
263 stripslashes — 따옴표 처리한 문자열을 풉니다 2016.12.23 20486
262 quotemeta 모든 메타 문자앞에 역슬래쉬를 붙인 문자열을 반환 2016.12.23 20461
261 stripcslashes — addcslashes()로 인용한 문자열을 되돌림 2016.12.23 20442
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 17 Next
/ 17

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved