2010-03-19 5 views
1

mySQL 테이블을 가져와 .XLS 형식으로 내 보낸 다음 웹 호스트의 지정된 폴더에 저장하는 스크립트를 만들어야합니다.fwrite로 .xls 파일 저장

나는 작동 시키지만 이제는 사용자에게 메시지를 표시하지 않고 파일을 자동으로 위치에 저장하는 것처럼 보이지 않습니다.

웹 호스트의 .XLS 파일로 이전 날짜를 저장할 수 있도록 매일 지정된 시간에 실행해야합니다. 여기

코드입니다 :

<?php 

// DB TABLE Exporter 
// 
// How to use: 
// 
// Place this file in a safe place, edit the info just below here 
// browse to the file, enjoy! 

// CHANGE THIS STUFF FOR WHAT YOU NEED TO DO 

    $dbhost = "-"; 
    $dbuser = "-"; 
    $dbpass = "-"; 
    $dbname = "-"; 
    $dbtable = "-"; 

// END CHANGING STUFF 

$cdate = date("Y-m-d"); // get current date 


// first thing that we are going to do is make some functions for writing out 
// and excel file. These functions do some hex writing and to be honest I got 
// them from some where else but hey it works so I am not going to question it 
// just reuse 


// This one makes the beginning of the xls file 
function xlsBOF() { 
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); 
    return; 
} 

// This one makes the end of the xls file 
function xlsEOF() { 
    echo pack("ss", 0x0A, 0x00); 
    return; 
} 

// this will write text in the cell you specify 
function xlsWriteLabel($Row, $Col, $Value) { 
    $L = strlen($Value); 
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L); 
    echo $Value; 
    return; 
} 



// make the connection an DB query 
$dbc = mysql_connect($dbhost , $dbuser , $dbpass) or die(mysql_error()); 
mysql_select_db($dbname); 
$q = "SELECT * FROM ".$dbtable." WHERE date ='$cdate'"; 
$qr = mysql_query($q) or die(mysql_error()); 


// Ok now we are going to send some headers so that this 
// thing that we are going make comes out of browser 
// as an xls file. 
// 
header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Content-Type: application/force-download"); 
header("Content-Type: application/octet-stream"); 
header("Content-Type: application/download"); 

//this line is important its makes the file name 
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls "); 

header("Content-Transfer-Encoding: binary "); 

// start the file 
xlsBOF(); 

// these will be used for keeping things in order. 
$col = 0; 
$row = 0; 

// This tells us that we are on the first row 
$first = true; 

while($qrow = mysql_fetch_assoc($qr)) 
{ 
    // Ok we are on the first row 
    // lets make some headers of sorts 
    if($first) 
    { 
     foreach($qrow as $k => $v) 
     { 
      // take the key and make label 
      // make it uppper case and replace _ with ' ' 
      xlsWriteLabel($row, $col, strtoupper(ereg_replace("_" , " " , $k))); 
      $col++; 
     } 

     // prepare for the first real data row 
     $col = 0; 
     $row++; 
     $first = false; 
    } 

    // go through the data 
    foreach($qrow as $k => $v) 
    { 
     // write it out 
     xlsWriteLabel($row, $col, $v); 
     $col++; 
    } 
    // reset col and goto next row 
    $col = 0; 
    $row++; 
} 

xlsEOF(); 
exit(); 
?> 

나는 이러한 목표를 달성하기에 fwrite를 사용하여 시도,하지만 아주 잘 갈 것 같지 않았다, 나는 너무 헤더 정보를 제거으나 효과가 없었다.

여기에 원래 코드가 있습니다. 찾았을 때 도움이 될 것입니다. :-)

고지. :-)

+0

브라우저에 보낼 헤더가 있지만 웹 호스트의 파일 시스템에 저장하는 방법에 대해 이야기합니다. 당신은 당신이 시도하고있는 것과 그 중 어느 것이 당신이 문제/예기치 않은 결과를 가져 왔는지에 대해 더 설명 할 수 있습니까? –

+0

웹 호스트에 저장하고 싶습니다. cron 작업을 통해 지정된 시간에 매일 실행되기 때문에 머리글이 필요 없습니다. – Odyss3us

답변

3

먼저, cron을 통해 디스크에 저장하기 때문에 의심되는 모든 header() 호출을 제거해야합니다. 가능한 적은 코드를 다시 작성하려면 출력 버퍼링 (http://www.php.net/manual/en/ref.outcontrol.php)을 사용하는 것이 좋습니다. 파일 출력하기 전에()위한 ob_start하기 위해 전화를 걸,이 작업을 수행하기 시작합니다

ob_start(); 
// start the file 
xlsBOF(); 

그리고 당신의 출력단 후

, 출력 버퍼를 닫 내용을 캡처하고 파일에 쓰기 :

xlsEOF(); 
// $filename should be set to some writeable location 
file_put_contents($filename, ob_get_clean()); 
+0

그건 마술을 한 것 같아, 고맙습니다 백만! – Odyss3us

1

xls 또는 xsl 파일 형식입니까? 나를 혼란스럽게 만들었습니다.

첫째 :

  • 가 나는 XLS 것 같아요 여러 탭을 사용 수식을 사용하여 글꼴 스타일을 설정해야합니까? 그렇다면 phpwriteexcel과 같은 Excel 라이브러리를 찾으십시오.

    그렇지 않으면 간단한 csv 파일로 충분합니다 (쉼표로 구분 된 값, 배열에서 매우 쉽게 작성, Excel 및 기타 스프레드 시트 소프트웨어로 완벽하게 읽음).

    그런 다음 메시지를 표시하지 않고 자동으로 저장하려면 : 계획된 작업/cron 작업으로 이동하여 스크립트를 호출하십시오.

+0

그것은 Microsoft Excel xls 파일, 죄송합니다. – Odyss3us

+0

아니요, 이건 기본적으로 출력하고 싶습니다.하지만 파일을 다운로드 할 때마다 cron 작업을 실행할 때마다 스크립트가있는 디렉토리에 파일을 저장해야합니다. 내가 fwrite를 사용할 수 있다고 가정하고 있습니까? 하지만이 코드에 어떻게 통합 할 것인가? 나는 csv 파일을 시도했지만, 꽤 잘 작동했지만, 불행히도 xls 형식이어야합니다. 고맙다. – Odyss3us

3

여기에 마지막 코드가 있는데, 그것은 매력처럼 작동합니다.

<?php 

    // DB TABLE Exporter 
    // 
    // How to use: 
    // 
    // Place this file in a safe place, edit the info just below here 
    // browse to the file, enjoy! 

    // CHANGE THIS STUFF FOR WHAT YOU NEED TO DO 
     $cdate = date("Y-m-d"); 
     $dbhost = "-"; 
     $dbuser = "-"; 
     $dbpass = "-"; 
     $dbname = "-"; 
     $dbtable = "-"; 
     $filename = "exported_on_$cdate.xls"; 

    // END CHANGING STUFF 


    // first thing that we are going to do is make some functions for writing out 
    // and excel file. These functions do some hex writing and to be honest I got 
    // them from some where else but hey it works so I am not going to question it 
    // just reuse 


    // This one makes the beginning of the xls file 
    function xlsBOF() { 
     echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); 
     return; 
    } 

    // This one makes the end of the xls file 
    function xlsEOF() { 
     echo pack("ss", 0x0A, 0x00); 
     return; 
    } 

    // this will write text in the cell you specify 
    function xlsWriteLabel($Row, $Col, $Value) { 
     $L = strlen($Value); 
     echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L); 
     echo $Value; 
     return; 
    } 



    // make the connection an DB query 
    $dbc = mysql_connect($dbhost , $dbuser , $dbpass) or die(mysql_error()); 
    mysql_select_db($dbname); 
    $q = "SELECT * FROM ".$dbtable." WHERE date ='$cdate'"; 
    $qr = mysql_query($q) or die(mysql_error()); 

    //start the object 
    ob_start(); 

    // start the file 
    xlsBOF(); 

    // these will be used for keeping things in order. 
    $col = 0; 
    $row = 0; 

    // This tells us that we are on the first row 
    $first = true; 

    while($qrow = mysql_fetch_assoc($qr)) 
    { 
     // Ok we are on the first row 
     // lets make some headers of sorts 
     if($first) 
     { 
      foreach($qrow as $k => $v) 
      { 
       // take the key and make label 
       // make it uppper case and replace _ with ' ' 
       xlsWriteLabel($row, $col, strtoupper(ereg_replace("_" , " " , $k))); 
       $col++; 
      } 

      // prepare for the first real data row 
      $col = 0; 
      $row++; 
      $first = false; 
     } 

     // go through the data 
     foreach($qrow as $k => $v) 
     { 

      // write it out 
      xlsWriteLabel($row, $col, $v); 
      $col++; 
     } 

     // reset col and goto next row 
     $col = 0; 
     $row++; 

    } 

    xlsEOF(); 

    //write the contents of the object to a file 
    file_put_contents($filename, ob_get_clean()); 

    ?> 

고맙습니다.

+0

특정 수의 행을 거친 후 새 워크 시트를 추가하는 방법이 있습니까? – Jeeva