muruga
muruga

Reputation: 2122

How to download a Excel sheet from the PHP code

I have written the code for getting data from the database and store it in the Excel sheet.I want to download the excel file only. But the following code give the PHP file output as my excel file content. But I need to download the Excel file which is created in the PHP file.

 <?php 
 $start_date="01/06/2010";
          $end_date="23/06/2010";
          $filename=$user.".xls";

          require 'DB.php' ; 
          include 'Spreadsheet/Excel/Writer.php'; 
          $excel = new Spreadsheet_Excel_Writer($filename);
          $format_bold =& $excel->addFormat();
          $format_bold->setBold();
          $format_bold->setColor('red'); 
          $sheet= $excel->addWorksheet('Class I');
          $sheet->write(0, 0, "Field Name",$format_bold);
          $sheet->write(0, 1,"Field Name", $format_bold);
          $sheet->write(0, 2, "Filed Name",$format_bold); 
          $sheet->write(0, 3,"Filed name", $format_bold);
          $db = DB::connect( connect query);
          $q=$db->getAll("select * from table_name"); 
          $rowCount=1;
         foreach ($q as $row)
         {
                foreach ($row as $key => $value) 
                 {
                    $sheet->write($rowCount, $key, $value);
                 }
      $rowCount++;
        }
header('Pragma: no-cache');
header('Expires: 0');
header("Content-type: application/x-msexcel");
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename="'$filename'"');
?> 

Upvotes: 0

Views: 3051

Answers (2)

GOsha
GOsha

Reputation: 689

header ( "Expires: Mon, 1 Apr 1974 05:00:00 GMT" );
header ( "Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT" );
header ( "Cache-Control: no-cache, must-revalidate" );
header ( "Pragma: no-cache" );
header ( "Content-type: application/x-msexcel" );
header ( 'Content-Disposition: attachment; filename="'.$filename.'"' );
header ( "Content-Description: PHP Generated XLS Data" );
print $sheet;

Is error_reporting(); switched to max lvl?

Upvotes: 0

mfloryan
mfloryan

Reputation: 7685

You need to add a call to the send() method to generate the content. This way you also don't need any of the headers as the method will generate them for you.

$excel->send($filename);

Upvotes: 1

Related Questions