Isaac Gonzalez
Isaac Gonzalez

Reputation: 1734

How do I output EXCEL file directly to user without storing locally?

I'm using PHPExcel to generate excel files (crazy right ?) with information I get from a database, the thing is whenever I create the file it is saved in the server and then I just send a link to that file to the user so he can access it.

I doubt this is the right way of doing it, what I'm looking for is to just send the file to the browser without saving it on the server.

How do I output EXCEL file directly to user without storing locally?

Code:

$fileName  = "Request_" . $idRequest . "_Update.xls";
$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
$objWriter->save($fileName);
$objPHPExcel = PHPExcel_IOFactory::load($fileName);


echo json_encode(array(
        "ExitCode" => 0,
        "Message" => "Success",            
        "data" => $request,
        "File" => "../reports/$fileName"
    ));

Once i receive File in the $.ajax call that receives it just add it to an anchor tag:

$.ajax({
       ...
       success : function(response){
           $('#container').append('<a href="'+response.File+'">Here is your file</a>
       }

Upvotes: 0

Views: 4901

Answers (3)

Mark Baker
Mark Baker

Reputation: 212412

The accepted response to this question shows how to handle a success response be offering the file for download, or a failure response handled by the js (e.g. displayed within the current html page) without mime type issues

Upvotes: 1

Snow Blind
Snow Blind

Reputation: 1164

You can send a

header("Content-Disposition: attachment; filename=\"file.xls\"");

to force download and then

header("Content-type:application/vnd.ms-excel");

to say the browser that you're sending an excel file and finally just echo the file as an html table:

<?php
header("Content-Disposition: attachment; filename=\"file.xls\"");
header("Content-type:application/vnd.ms-excel");
echo "<html><table>...</table></html>";  // your table data here..
?>

Excel can open .html files with <table>s so there shouldn't be any problem.

Upvotes: 1

vishal
vishal

Reputation: 705

check this out.

//    reset all output buffering
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    header('Content-type: application/ms-excel');
    header('Content-Disposition:  inline; attachment; filename='.$filename);

    // we can't send any more headers after this
    flush();

    $excel = new PhpExcel();
    $excel->setActiveSheetIndex(0);
    $sheet = $excel->getActiveSheet();
    // in this example, $data was an array in the format row => value
    //  data structure is not relevant to issue
    foreach ($data as $key => $value) {
         // add data to sheet here
         $sheet->SetCellValue('A' . $key, $value);
         // etc...
    }
    $writer = new PHPExcel_Writer($excel);
    // push to browser
    $writer->save('php://output');

Upvotes: 2

Related Questions