Saturday, November 11, 2017

phpMyPassion

How To Generate And Download A Dynamic Excel Sheet Using PHP ?


I have got lot of queries regarding to generate an excel sheet and download that on the system using PHP. So I thought to share the proper solution with an article.



You can download an excel by using two process. either you can use function to download excel sheet or you can use PHP code on the same page to download a dynamic excel sheet.

So here I describing both the process. you can use according to your ease.

#Process 1: Downlode an excel using PHP script on same page.

 you can download an excel using the script on same page as below code.

<?php 
$report = array(array('id'=>1,'name'=>'raj'),array('id'=>2,'name'=>'monica'),array('id'=>3,'name'=>'sonia'));
$t = time();
$filename = 'excel_report-'.$t.'.xls';
echo '<table class="table table-responsive table-hover " border="1" ><tbody>';
// Display results.
foreach($report as $row) {   
    echo '<tr>';
    foreach($row as $column) {
     // printf('%25s', $column);?>
       <td><?php echo $column; ?></td>
      <?php
    }
    print "</tr>";
}  
print "</tbody></table>";
@header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "filename.xls"
@header("Content-Disposition: attachment; filename=".$filename); 

#Process 1: Downlode an excel using function.

 you can download an excel using the PHP function as below steps.

#Step 1: Create a index.php as below


<?php 
include 'functions.php';
$function = new functions();

$report = array(array('id'=>1,'name'=>'raj'),array('id'=>2,'name'=>'monica'),array('id'=>3,'name'=>'sonia'));

$function->downloadExcel($report);

#Step 2 : Now create a class file with the name functions.php as below.

<?php 
Class functions{
    public function downloadExcel($report){
        $t = time();
        $filename = 'excel_report-'.$t.'.xls';
        echo '<table class="table table-responsive table-hover " border="1" ><tbody>';
        // Display results.
        foreach($report as $row) {   
            echo '<tr>';
            foreach($row as $column) {
             // printf('%25s', $column);?>
               <td><?php echo $column; ?></td>
              <?php
            }
            print "</tr>";
        }  
        print "</tbody></table>";
        @header("Content-type: application/vnd-ms-excel");
        // Defines the name of the export file "filename.xls"
        @header("Content-Disposition: attachment; filename=".$filename); 
    }
} 


if you run the index.php file on browser, you will see the downloaded excel sheet.



Improve this sample solution and post your code by Comment.



About Author -

Hi, I am Anil.

Welcome to my eponymous blog! I am passionate about PHP programming. Here you will find a hug of information on web development, web design, PHP and Latest technology.

Subscribe to this Blog via Email :