How to create excel file and save to server / download

03rd, January 2018 By

Today we will learn how to create excel file from data in php and save the excel file on the server.Some time for various reasons like for backup etc we need to create excel file of our data and save that to server.Its very easy to do and following few steps you will able to do it easily.

 

Excel Save

Download Excel Library

For creating excel file you will need the excel library .You will download the excel file library from here after signup.

PHP Code For Create Excel File & Server Save


<?php

require_once "excel.php";
$yourFile = "xlsfile://Your folder/example.xls";
$file = fopen($export_file, "wb");
if (!is_resource($fp))
{
die("Cannot open $export_file");
}

// typically this will be generated/read from a database table
$assoc = array(
array("Name" => "deepak", "Email" => "info@websexpert.net", "Gender" => "$m"),
array("Name" => "deepak", "Email" => "info@websexpert.net", "Gender" => "$m"),
array("Name" => "deepak", "Email" => "info@websexpert.net", "Gender" => "$m"),
);

fwrite($file, serialize($assoc));
fclose($file);
?>

The code
require_once “excel.php”;
$yourFile = “xlsfile://Your folder/example.xls”;

will save the file on server like here example.xls on you server.

where your folder = folder name  you want to save file.

Next step we will open the file and write in it our data then close it.

Solved Issue on Excel.php

If you are facing problem of not saving the file on server.Please open your library excel file that is excel.php.

Goes to line 74,you will see code like this

$this->xlsfilename = ‘/’ . $url[‘host’] . $url[‘path’];

Remove the / from this code and new code look like it.

$this->xlsfilename = $url[‘host’] . $url[‘path’];

This will solved the issue of file not saving on your server.

Browser Download

If you want the excel file is saved on your browser ,just copy and paste these headers that will work for saving the file on your browser.


<code><?php
require_once "excel.php";
$export_file = "xlsfile://tmp/example.xls";
header ("Expires: Mon, 26 Jul 2013 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=\"" . basename($excel_file) . "\"" );
header ("Content-Description: PHP/INTERBASE Generated Data" );
readfile($excel_file);
exit;
?> </code>

This code will download the your excel file on the browser.Hope this will help you for creating and saving excel file on server.

Leave a Reply

Your email address will not be published. Required fields are marked *