티스토리 뷰

php

php 엑셀 읽기 쓰기 - PHPExcel

xemaker 2018. 4. 19. 14:11
먼저 엑셀을 읽을려면 엑셀 파일이 있어야 하니 엑셀 쓰기먼저

<?php
// PHPExcel.php을 불러와야 하며, 경로는 사용자의 설정에 맞게 수정해야 한다.

require_once "./PHPExcel-1.8/Classes/PHPExcel.php";

$objPHPExcel = new PHPExcel();
// IOFactory.php을 불러와야 하며, 경로는 사용자의 설정에 맞게 수정해야 한다.
require_once "./PHPExcel-1.8/Classes/PHPExcel/IOFactory.php";
 $filename = './test.xls'; // 읽어들일 엑셀 파일의 경로와 파일명을 지정한다.
 $objPHPExcel = new PHPExcel();
//엑셀 row는 1번 부터 시작함. $objPHPExcel->setActiveSheetIndex(0) ->setCellValue("A1", "홍길동") ->setCellValue("B1", "seoul") ->setCellValue("A2", "성춘향") ->setCellValue("B2", "busan");
// Rename sheet $objPHPExcel->getActiveSheet()->setTitle('Sheet 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", "테스트.xls");
// 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;


결과:
위에것을 실행하면 test.xls 파일이 만들어 지고 열어보면 아래와 같이 되어 있다.

홍길동

seoul

성춘향

busan



다음은 엑셀 읽기
위에서 만들어진 엑셀 파일을 읽는다.

<?
// PHPExcel.php을 불러와야 하며, 경로는 사용자의 설정에 맞게 수정해야 한다.
require_once "./PHPExcel-1.8/Classes/PHPExcel.php";
$objPHPExcel = new PHPExcel();
// IOFactory.php을 불러와야 하며, 경로는 사용자의 설정에 맞게 수정해야 한다.
require_once "./PHPExcel-1.8/Classes/PHPExcel/IOFactory.php";
$filename = './test.xls';
// 읽어들일 엑셀 파일의 경로와 파일명을 지정한다.
try {
// 업로드 된 엑셀 형식에 맞는 Reader객체를 만든다.
$objReader = PHPExcel_IOFactory::createReaderForFile($filename);
// 읽기전용으로 설정
$objReader->setReadDataOnly(true);
// 엑셀파일을 읽는다
$objExcel = $objReader->load($filename);
// 첫번째 시트를 선택
$objExcel->setActiveSheetIndex(0);
$objWorksheet = $objExcel->getActiveSheet();
$maxRow = $objWorksheet->getHighestRow();
//엑셀 row는 1번 부터 시작함.
for ($i = 1 ; $i <= $maxRow ; $i++) { $a = $objWorksheet->getCell('A' . $i)->getValue();
// A열
$b = $objWorksheet->getCell('B' . $i)->getValue();
// B열
$c = $objWorksheet->getCell('C' . $i)->getValue();
// C열
echo $a;
echo $b;
echo $c;
echo "<br>\n";
}
} catch (exception $e) {
echo '엑셀파일을 읽는도중 오류가 발생하였습니다.';
}
/*
$rowIterator = $objWorksheet->getRowIterator();
foreach ($rowIterator as $row) {
// 모든 행에 대해서
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
}
*/


결과:
홍길동seoul
성춘향busan


 http://phpexcel.codeplex.com
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함