'2018/02/27'에 해당되는 글 1건

728x90

아래 코드는 MySQL DB 테이블에 있는 자료를 CSV 파일로 저장하는 예제다.

while 문을 사용하면 4만개 정도의 데이터도 매우 빠르게 저장된다.

for문, foreach문을 사용하면 매우 느리다.

저장된 데이터를 엑셀에서 읽었을 때 깨져보이면 charset=utf-8 를 charset=euc-kr 로 저장하면 될 것이다.

자료 저장 형태가 CSV 라는 것은 EditPlus 와 같은 툴로 읽어도 내용이 보인다는 거다.

그러므로 엑셀에서 수정하고 저장할 때 반드시 다른 이름으로 저장을 선택하여 저장형식을 엑셀 형식으로 저장해야 한다. 바로 저장을 하면 파일 구조가 web 파일 형태로 저장되어 이상하게 보일 것이다.


<?php
if(!isset($_SESSION)) {
    session_start();
}

$file_name = "Park.xls";
header( "Content-type: application/vnd.ms-excel; charset=euc-kr");
header( "Cache-Control: must-revalidate, post-check=0,pre-check=0" );
header( "Content-Disposition: attachment; filename=".$file_name);
header( "Content-Description: PHP4 Generated Data" );


include_once '../dbinfo.php';
include_once '../dbconnect.php'; // DB 접속

$tblName = data;    // 테이블명
$result = mysql_query("SELECT uid, (select classname from category where uid=data.category1) as cate1,(select classname from category where uid=data.category2) as cate2,content FROM $tblName where sysrole = 0 ORDER BY uid DESC", $dbconn);
// DESC 내림차순 정렬, ASC 오름차순 정렬

// 테이블 상단 만들기
$EXCEL_STR = "
<table border='1'>
<tr>
<td ALIGN=CENTER BGCOLOR='#9DEEE1'>UID</td>
<td ALIGN=CENTER BGCOLOR='#9DEEE1'>구분1</td>
<td ALIGN=CENTER BGCOLOR='#9DEEE1'>구분2</td>
<td ALIGN=CENTER BGCOLOR='#9DEEE1'>내용</td>
</tr>";

while ($row = mysql_fetch_array($result) ){
    $EXCEL_STR .= "
    <tr>
    <td ALIGN=CENTER>".$row['uid']."</td>   
    <td ALIGN=CENTER>".$row['cate1']."</td>
    <td ALIGN=CENTER>".$row['cate2']."</td>
    <td>".stripslashes($row['content'])."</td> 
    </tr>
    ";
}

$EXCEL_STR .= "</table>";
echo $EXCEL_STR;
mysql_free_result ($result);

exit;

?>

블로그 이미지

Link2Me

,