티스토리 뷰

IT Story/Programing

PHP에서 Excel 파일 읽기/쓰기

행복한소식까치 2014. 7. 29. 14:59
반응형
PHP - Excel 내려받기

 

문서의 해드에 아래 소스를 추가합니다.

 

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=파일명.xls");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
header("Pragma: public");

 

위 파일을 추가 했을때 아래와 같은 오류가 나올경우 해경 방법

 

오류 메시지

Warning: Cannot modify header information - headers already sent by
(output started at 파일경로명/php_excel/excel_export.php:16)
in 파일경로명/php_excel/excel_export.php on line 70

 

원인및 해결 방법

원인은 문서의 해드 아래에 해드 변화 소스를 입력했기 때문입니다.

 

즉 ) 아래와 같이 코딩하면 오류 메시지 나옵니다.

<html>

<head>

소스코딩

</head>

<body>

<?

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=파일명.xls");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
header("Pragma: public");

?>

</body>

</html>

 

올바른 사용예는 아래와 같습니다.

<?

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=파일명.xls");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
header("Pragma: public");

?>

<html>

<head>

소스코딩

</head>

<body>

 

</body>

</html>

 

PHP 에서 Excel 파일 읽어 DB에 저장 방법

 

http://code.google.com/p/php-excel-reader/

 

위 주소에서 php-excel-reader  를 다운로드 하여 사용.

 

기본 사용 방법은 example.php를 참조하면 됩니다.

 

엑셀 로단위로 읽어 DB에 저장하게 수정한 소스는 아래와같습니다.

 

<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader("파일명.xls");
?>
<html>
<head>
</head>

<body>
<?php
  $server = "localhost"; //서버 이름
  $id    = ""; //db 접속 아이디
  $pass   = ""; //디비 접속 비밀번호
  $connect = mysql_connect($server,$id,$pass);
  mysql_select_db("dbname",$connect);
 
 
 // 엑셀 첫번째 sheet 행 개수
 $rowcount = $data->rowcount($sheet_index=0);
 
 for($i=2 ;$i<=$rowcount; $i++){
 /*
   echo $data->val($i,2)." ";
   echo "point:".$data->val($i,3)." ";
   echo "id:".$data->val($i,4)." ";
 */ 

  
     //val(행,열)
  $ID    = $data->val($i,4);
  $Point = $data->val($i,3);

 


  $QUE = "Sql Query";
     $ok = mysql_query($QUE , $connect) or die(db_error());

 
 
    } 

?>
</body>
</html>
 

반응형
댓글