2010-03-19 2 views
1

Мне нужно создать скрипт, который принимает таблицу mySQL, и экспортирует его в формат .XLS, а затем сохраняет этот файл в указанную папку на веб-узле.Сохранение файла .xls с помощью fwrite

Я получил его работу, но теперь я не могу заставить его автоматически сохранять файл в папку без запроса пользователя.

Он должен запускаться каждый день в указанное время, поэтому он может сохранять предыдущие дни в файле .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 для достижения этой цели, но это, похоже, не идут очень хорошо, я удалил информацию заголовка тоже, но ничего не получалось.

Это оригинальный код, так как я нашел его, любая помощь будет принята с благодарностью. :-)

Thanx заранее. :-)

+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:

Первое: вам нужно настроить стили шрифтов, использовать несколько вкладок, использовать формулы? Если это так, попробуйте воспользоваться библиотекой excel, такой как phpwriteexcel.

В противном случае достаточно простого csv-файла (значение, разделенное запятыми, созданное очень легко из массивов, отлично читаемое с помощью Excel и других программных продуктов для электронных таблиц).

Затем, чтобы сохранить его автоматически, не запрашивая: перейдите к запланированной задаче задачи/cron, вызвав ваш скрипт.

+0

Это файл Microsoft Excel xls, извините, что. – Odyss3us

+0

Нет, я не делаю этого, это в основном выводит его так, как хотелось бы, но я не буду там каждый раз, когда он запускается через задачу cron, чтобы загрузить файл, поэтому мне нужно, чтобы он сохранил файл в каталоге, который скрипт Я предполагаю, что могу использовать fwrite для этого? Но как я могу интегрировать это в этот код? Я пробовал файл csv, он работал очень хорошо, но, к сожалению, он должен быть в формате xls. Thanx снова за помощью. – 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()); 

    ?> 

Thanx для всех парней помощи!

+0

Есть ли способ добавить новый лист после исключения определенного количества строк – Jeeva

Смежные вопросы