PHP

[PHP] php_writeexcel 이용 .xls 파일 생성

chsr 2022. 2. 17. 13:16
728x90
반응형

■ PHP php_writeexcel 이용 .xls 파일 생성 


PHP에서 .xls 파일 생성 시 대부분 PHPExcel을 사용하지만
최소 php 5.2 이상이어야 가능하기 때문에 다른 라이브러리를 사용해야할 때가 있음
많은 라이브러리 중 php_writeexcel 에 대한 사용법을 정리함


■ php_writeexcel

http://www.bettina-attack.de/jonny/view.php/projects/php_writeexcel/

 

bettina-attack.de

 

www.bettina-attack.de


■ 사용법

배열에 저장된 값에 문자 변환 함수 적용을 위해 array_map 함수 사용함

<?
    include_once('./lib/php_writeexcel/class.writeexcel_workbook.inc.php');
    include_once('./lib/php_writeexcel/class.writeexcel_worksheet.inc.php');

    $fname = tempnam("/tmp", "tmp-orderlist.xls");
    $workbook = new writeexcel_workbook($fname);
    $worksheet = $workbook->addworksheet();

    // Put Excel data
    $data = array('우편번호', '주소', '이름', '전화1', '전화2', '상품명', '수량', '선택사항', '배송비', '상품코드', '주문번호', '운송장번호', '전하실말씀');
    $data = array_map('iconv_euckr', $data);

    <?php
    $col = 0;
    foreach($data as $cell) {
        $worksheet->write(0, $col++, $cell);
    }

    for($i=1; $row=mysql_fetch_array($result); $i++) {
        $sendcost = iconv_euckr(($row['sendcost'] ? '착불' : '선불'));
        $row = array_map('iconv_euckr', $row);

        $worksheet->write($i, 0, $row['zip1'].'-'.$row['zip2']);
        $worksheet->write($i, 1, $row['addr1'].' '.$row['addr2']);
        $worksheet->write($i, 2, $row['name']);
        $worksheet->write($i, 3, $row['tel']);
        $worksheet->write($i, 4, $row['hp']);
        $worksheet->write($i, 5, $row['item']);
        $worksheet->write($i, 6, $row['qty']);
        $worksheet->write($i, 7, $row['option']);
        $worksheet->write($i, 8, $sendcost);
        $worksheet->write($i, 9, $row['item_id']);
        $worksheet->write($i, 10, $row['order_id']);
        $worksheet->write($i, 11, $row['invoice']);
        $worksheet->write($i, 12, $row['memo']);
    }

    $workbook->close();

    header("Content-Type: application/x-msexcel; name="orderlist-".date("ymd", time()).".xls"");
    header("Content-Disposition: inline; filename="orderlist-".date("ymd", time()).".xls"");
    $fh=fopen($fname, "rb");
    fpassthru($fh);
    unlink($fname);

    exit;
    
    // utf-8 문자 euc-kr 변환
    function iconv_euckr($str){
        return iconv('utf-8', 'euc-kr', $str);
    }
?>
728x90
반응형