테스트 사이트 - 개발 중인 베타 버전입니다

엑셀 xlsx 로 저장 방법

· 2년 전 · 3678 · 32

 

GitHub - mk-j/PHP_XLSXWriter: Lightweight XLSX Excel Spreadsheet Writer in PHP

 

xlsxwriter.class.php 파일 다운받아 lib 폴더에 넣어 주세요( 이 파일만 필요합니다.)

 

아래 코드를 excel_view.php 로 저장해서 엑셀로 저장하고 싶은 데이터가 있는 스킨폴더에 복사

 

필요한 위치에 아래처럼 링크를 걸어 사용하시면 됩니다. 

현재 코드는   &wr_id=<?=$list[$i]['wr_id'] 를 이용해 wr_id 기준으로 검색하는 예시입니다.

생략하면 $bo_table 전체데이터를 저장합니다. $result 쿼리 구문도 수정해 줘야됩니다.

 

<a href="<?= $board_skin_url?>/excel_view.php?bo_table=<?=$bo_table?>&wr_id=<?=$list[$i]['wr_id']?>" class="btn_b01 btn">엑셀다운</a>

 

 [code]

<?php
include_once('./_common.php');

set_include_path(get_include_path().PATH_SEPARATOR."..");
include_once(G5_LIB_PATH."/xlsxwriter.class.php");

 

$writer = new XLSXWriter();

 

$wr_id = isset($_GET['wr_id']) ? intval($_GET['wr_id'])  : 0;

$bot_table = $g5['write_prefix'].$bo_table;

 

$filename = "테스트신청현황.xlsx";

$filepath1 = G5_DATA_PATH.'/tmp/'.$filename;

 

$header = [];
$widths = [];

$contents = [];

 

// $header 제목명은 모두 달라야 됨, 뒤에 여러 서식을 지정할 수 있습니다.(위 github 참조) 
$header["연번"] = 'integer';
$header["예약자"] = 'string';
$header["예약일자"] = 'string';
$header["예약시간"] = 'string';
$header["전화번호"] = 'string';
$header["성별"] = 'string';
$header["요청사항"] = 'string';
$header["신청일"] = 'string';

 

//셀너비- 순서대로 알맞게 지정
$widths[] = 10; $widths[] = 20; $widths[] = 20; $widths[] = 20; $widths[] = 20; $widths[] = 20;$widths[] = 50; $widths[] = 30;

 

$styles1 = array('font'=>'맑은 고딕','font-size'=>12,'font-style'=>'bold', 'fill'=>'#ccff999', 'halign'=>'left', 'valign'=>'center', 'border'=>'left,right,top,bottom', 'widths'=>$widths);

$styles2 = array('font'=>'맑은 고딕','font-size'=>12, 'halign'=>'left', 'valign'=>'center', 'border'=>'left,right,top,bottom','wrap_text'=>true);
 

$writer->writeSheetHeader('Sheet1', $header, $styles1);    //제목줄 서식 포함

 

// 가져올 쿼리 구문

$result = sql_query("select * from {$bot_table} where wr_id = '{$wr_id}' order by wr_name");

foreach ($result as $key=>$field) {
    $contents[] = ($key + 1);
    $contents[] = $field['wr_name'];
    $contents[] = $field['wr_1'];
    $contents[] = $field['wr_2'];
    $contents[] = $field['wr_3'];
    $contents[] = $field['wr_4'];
    $contents[] = $field['wr_content'];
    $contents[] = $field['wr_last'];

    $writer->writeSheetRow('Sheet1', $contents, $styles2);
    $contents = [];
}

$writer->writeToFile($filepath1);

 

//아래부분은 수정할 필요 없습니다.
$filepath = addslashes($filepath1);
$original = urlencode($filename);

if(preg_match("/msie/i", $_SERVER["HTTP_USER_AGENT"]) && preg_match("/5\.5/", $_SERVER["HTTP_USER_AGENT"])) {
    header("content-type: doesn/matter");
    header("content-length: ".filesize("$filepath"));
    header("content-disposition: attachment; filename=\"$original\"");
    header("content-transfer-encoding: binary");
} else if (preg_match("/Firefox/i", $_SERVER["HTTP_USER_AGENT"])){
    header("content-type: file/unknown");
    header("content-length: ".filesize("$filepath"));
    header("content-disposition: attachment; filename=\"".basename($filename)."\"");
    header("content-description: php generated data");
} else {
    header("content-type: file/unknown");
    header("content-length: ".filesize("$filepath"));
    header("content-disposition: attachment; filename=\"$original\"");
    header("content-description: php generated data");
}
header("pragma: no-cache");
header("expires: 0");
flush();

$fp = fopen($filepath, "rb");

if (!fpassthru($fp)) {
    fclose($fp);
}

 

//파일 삭제

if(file_exists($filepath1)) {
    @unlink($filepath1);
}

[/code]

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

댓글 32개

1년 전

@달료라 wr_id와 $bo_table 확인해 보세요.

아래 구문은 목록에서 하는 링크입니다.

<a href="<?= $board_skin_url?>/excel_view.php?bo_table=<?=$bo_table?>&wr_id=<?=$list[$i]['wr_id']?>" class="btn_b01 btn">엑셀다운</a>

도와주세요...

그대로 넣었는데 제목은 나오고 내용은 왜 출력이 안될까요...

1년 전

@자우림님 질문만으로는 원인을 알 수 없습니다.

$result = sql_query("select wr_~~~

$result 아래부분 모두 지우시고 

var_dump($result); 입력하여 내용이 나오는지 확인해 보세요.


 

@그누아치 

NULL 이 뜹니다.

1년 전

@자우림  쿼리구문에  검색되는 자료가 없는것 같습니다.

Echo $wr_id;

echo $bot_table;

도 해보세요.

전체검색시

where wr_id = '{$wr_id}' 

부분은 삭제해보세요.

 

 

@그누아치 

도움에 감사드립니다.

그누아치님 감사합니다. 너무 편리합니다^^

혹시  $contents[] = $field['mb_id']; 와 같이 처리를 할 때 mb_id의 값 대신에 mb_nick의 값으로 대체할 수 있는 방법이 있을까요? 해당 테이블에는 mb_nick의 값이 없습니다.

1년 전

@동글이

간단히 하면 아래처럼 하시면 되고, 아니면 위의 $result 구문을 left join 을 써서 결과값을 가져오는 방법이 있습니다.

foreach ($result as $field) {
    $result2 = sql_query("select mb_nick from g5_member where mb_id = '{$field['mb_id']}'");
    $x++;

~~~~

    $contents[] = $result2['mb_nick'];

~~~

@그누아치 질문답변에서 도움으로 join을 이용했었는데, 역시 그누아치님은 더 쉬운 방법을 제시해 주시네요.

감사합니다. ^^

5개월 전

문의 드립니다.

현재 PHP 5.3.3 일경우 제대로 작동이 되지 않습니다.

처음에 

$header = [];
$widths = [];
$contents = [];

배열을 지정하고 foreach 문에서 $contents = []; 에서 에러가 나네요.

어떻게 수정을 해야 하나요..

도움을 부탁드립니다.

게시글 목록

번호 제목
24318
24317
24315
24309
24294
24293
24277
24262
24260
24253
24251
24236
24233
24228
24226
24221
24214
24203
24201
24199
24196
24195
24194
24192
24191
24187
24185
24183
24172
24168