PHP 로 Excel 파일 읽기

프로그래밍/PHP|2020. 8. 21. 08:36
반응형

[출처1] http://www.joshi.co.kr/index.php?mid=board_EudV58&page=7&document_srl=293319

[출처2] https://wickedmagic.tistory.com/584


출처의 내용을 진행하며 제가 필요한 내용으로 수정 하였습니다.



1. PHP 설치 필수 모듈 설치 (Ubuntu 18.04 기준)


# apt install php7.2-zip php7.2-xml php7.2-gd



2. PHPExcel-1.8.0 다운로드


https://github.com/PHPOffice/PHPExcel 에 접속해 압축파일을 통째로 다운로드 받고

소스 최상위 디렉토리에 압축해제 하면 아래와 같은 디렉토리가 생성 됩니다.


./PHPExcel-1.8.0



3. Excel 파일 업로드


아래 내용으로 file.xlsx 파일을 만들어서 소스 최상위 디렉토리에 업로드 했습니다.

1

아무개 

10

 2

귀요미

12 



4. Excel 읽는 PHP 코드 생성


# vi excel_upload.php


<html>

<form enctype="multipart/form-data" action="./excel_read.php" method="post">

<table border="1">

<tr>

<th style="background-color:#DCDCDC">파일</th>

<td><input type="file" name="excelFile"/></td>

</tr>

<tr>

<th style="background-color:#DCDCDC">등록</th>

<td style="text-align:center;"><input type="submit" value="업로드"/></td>

</tr>

</form>

</html> 



# vi excel_read.php


<?

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 = './file.xlsx'; // 서버에 올려진 파일을 직접 지정할 경우


// excel_upload.php 파일을 이용해 업로드 한 경우

$filename = $_FILES['excelFile']['tmp_name'];


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++) {

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

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

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

               echo $no . ", " . $name . ", " . $age . "<br>";

    }

}


catch (exception $e) {

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

}

?>



반응형

댓글()