메뉴 건너뛰기

프로그램언어

조회 수 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의 위치를 고려하여 프로그래밍 해야 할 것이다.


  1. No Image 06Mar
    by
    2017/03/06 Views 16610 

    PHP의 유동변수!? - $a1 ~ $a2 같은 형식의 변수를 반복문 돌릴때...

  2. No Image 12Jan
    by
    2023/01/12 Views 293 

    PHP웹 보안 취약점 TOP5(웹해킹)

  3. No Image 26Mar
    by
    2021/03/26 Views 311 

    PHP와 HTML과 자바스크립트의 관계

  4. No Image 14Sep
    by
    2018/09/14 Views 3548 

    PHP에서의 대칭 암호화/복호화 ― 간단한 예제에서 DB 입/출력까지

  5. No Image 08Jan
    by
    2019/01/08 Views 1807 

    php에서 체크박스 선택한 것 보여주기

  6. No Image 14Apr
    by
    2015/04/14 Views 22046 

    PHP에서 조건문 처리

  7. No Image 27Feb
    by
    2014/02/27 Views 31635 

    PHP에서 자바스크립트 값 가져오기

  8. No Image 29Aug
    by
    2018/08/29 Views 2465 

    PHP에서 자료, 데이터의 타입을 확인하는 방법, gettype()

  9. No Image 09Feb
    by
    2018/02/09 Views 10626 

    PHP에서 암호화 encrypt 복호화 decrypt 해서 값을 넘기기

  10. No Image 29Aug
    by
    2018/08/29 Views 2694 

    PHP에서 모든 세션 정보를 화면에 출력하는 방법

  11. No Image 19Feb
    by
    2017/02/19 Views 18431 

    PHP에서 데이터를 엑셀(Excel)로 저장

  12. No Image 19Feb
    by
    2019/02/19 Views 1554 

    PHP에서 UTF와 EUC-KR 변환

  13. No Image 27Feb
    by
    2014/02/27 Views 32777 

    PHP에서 PDF파일 생성하기

  14. PHP에서 Excel 파일을 만들 수 있는 PHPExcel

  15. PHP에서 CSV 파일 export

  16. No Image 06Mar
    by
    2017/03/06 Views 17875 

    PHP로 엑셀 자료 MySQL에 넣기

  17. No Image 27Feb
    by
    2014/02/27 Views 30257 

    PHP로 Excel 파일 만들기...

  18. No Image 06Mar
    by
    2017/03/06 Views 15769 

    php로 db 컨트롤 1

  19. phpMyAdmin WebMysql 에 CSV 엑셀 파일 업로드 입력하기 ( Excel / Upload / data / 데이터 / 데이타 )

  20. phpexcel을 이용한 PHP로 엑셀파일 읽기와 생성

Board Pagination Prev 1 ... 5 6 7 8 9 10 11 12 13 14 ... 17 Next
/ 17

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved