Php excel from html

In my php page i have a table and if the user requires he has to export that table to excel sheet..

The code for displaying the table is:

$sql=mysql_query("SELECT * FROM attendance WHERE (year = '" . 
mysql_real_escape_string($_SESSION['year']) . "') and ( branch= '" . 
mysql_real_escape_string(($_SESSION['branch'])). "') and ( sem= '" . 
mysql_real_escape_string(($_SESSION['sem'])). "') and (sec= '" . 
mysql_real_escape_string(($_SESSION['sec'])). "')"); print "<body 
background='bg.jpg'>";                                                  
Print "<br><br><BR><center><table border 
cellpadding=3><tr><th>idno</th><th>name</th><th>subject</th><th>Held 
Classes</th><th>Attended Classes</th></tr>";   
while($data=mysql_fetch_array( 
$sql ))   { 

echo "<tr><td>".$data['idno']." </td><td>".$data['name'] . " 
<td>".$data['subject']." </td><td>".$data['heldcls'] . " 
<td>".$data['attendcls']." </td>"; } 
Print "</table><br><br><form action = excel.php method = POST><input type = 
'submit' name = 'submit' Value = 'Export to excel'></form></center>";

how do i export this table to excel sheet. And what should b the code in excel.php. Please help me.. thank you in advance..

Freddy789's user avatar

asked Sep 22, 2012 at 5:28

Nandu's user avatar

1

Either you can use CSV functions or PHPExcel

or you can try like below

<?php
$file="demo.xls";
$test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>

The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Isaac's user avatar

Isaac

6251 gold badge13 silver badges30 bronze badges

answered Sep 22, 2012 at 5:31

NullPoiиteя's user avatar

NullPoiиteяNullPoiиteя

56.2k22 gold badges125 silver badges143 bronze badges

2

If all you want is a simple excel worksheet try this:

header('Content-type: application/excel');
$filename = 'filename.xls';
header('Content-Disposition: attachment; filename='.$filename);

$data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
    <!--[if gte mso 9]>
    <xml>
        <x:ExcelWorkbook>
            <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                    <x:Name>Sheet 1</x:Name>
                    <x:WorksheetOptions>
                        <x:Print>
                            <x:ValidPrinterInfo/>
                        </x:Print>
                    </x:WorksheetOptions>
                </x:ExcelWorksheet>
            </x:ExcelWorksheets>
        </x:ExcelWorkbook>
    </xml>
    <![endif]-->
</head>

<body>
   <table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>
</body></html>';

echo $data;

The key here is the xml data. This will keep excel from complaining about the file.

answered Mar 28, 2013 at 18:26

darkrat's user avatar

darkratdarkrat

6736 silver badges14 bronze badges

4

<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
    <tr bgcolor="#CCC">
      <td width="100">xxxxx</td>
      <td width="700">xxxxxx</td>
      <td width="170">xxxxxx</td>
      <td width="30">xxxxxx</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td><?php                 
            $date = date_create($row_Recordset3['fecha']);
            echo date_format($date, 'd-m-Y');
            ?></td>
      <td><?php echo $row_Recordset3['descripcion']; ?></td>
      <td><?php echo $row_Recordset3['producto']; ?></td>
      <td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
    </tr>
  </table>

  <input type="hidden" id="datatodisplay" name="datatodisplay">  
    <input type="submit" value="Export to Excel"> 

exporttable.php

<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>

answered Jul 28, 2014 at 15:28

Praveen Srinivasan's user avatar

Easiest way to export Excel to Html table

$file_name ="file_name.xls";
$excel_file="Your Html Table Code";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file_name");
echo $excel_file;

answered Oct 22, 2019 at 9:23

Love Kumar's user avatar

Love KumarLove Kumar

1,0409 silver badges10 bronze badges

2

HtmlPhpExcel

Build Status

This is a php library based on PhpSpreadsheet which simplifies converting html tables to excel files. It allows styling right within the html template with specific attributes.

Installation

Add HtmlPhpExcel to your composer.json:

composer require ticketpark/htmlphpexcel

Simple example

<?php

require_once('../vendor/autoload.php');

$html = '<table><tr><th>Column A</th><th>Column B</th></tr><tr><td>Value A</td><td>Value B</td></tr></table>';
$htmlPhpExcel = new TicketparkHtmlPhpExcelHtmlPhpExcel($html);

// Create and output the excel file to the browser
$htmlPhpExcel->process()->output();

// Alternatively create the excel and save to a file
$htmlPhpExcel->process()->save('myFile.xlsx');

// or get the PhpOfficePhpSpreadsheetSpreadsheet object to do further work with it
$phpExcelObject = $htmlPhpExcel->process()->getExcelObject();

For a more complex example with styling options see example directory.

Styling

There is support for specific html attributes to allow styling of the excel output. The attributes expect the content to be json_encoded.

  • _excel-styles
    Supports everything which is possible with PhpSpreadsheet’s applyFromArray() method (also see here).

Example:

<table>
    <tr>
        <td _excel-styles='{"font":{"size":16,"color":{"rgb":"FF0000"}}}'>Foo</td>
    </tr>
</table>
  • _excel-dimensions
    Supports changing dimensions of rows (when applied to a <tr> or <td>) or column (when applied to a <td>),

Example:

<table>
    <tr _excel-dimensions='{"row":{"rowHeight":50}}'>
        <td _excel-dimensions='{"column":{"width":20}}'>Foo</td>
    </tr>
</table>
  • _excel-explicit
    Supports applying an explicit cell value type.

Example:

<table>
    <tr>
        <td _excel-explicit='PhpSpreadsheet_Cell_DataType::TYPE_STRING'>0022</td>
    </tr>
</table>

Php

Show all


The web as a publishing platform has come on leaps and bounds over the last decade or two. HTML has gone from being a simple way to markup basic documentation to a fully-fledged interactive publishing medium. But it’s still useful to be able to convert HTML into other formats, especially for systems that involve a lot of data and require exportable reports.

For example, it’s often useful to be able to download or email PDF summaries of reports or invoices to clients. Or to offer the ability for customers on an ecommerce site to download their order details as a Word document.

To get started, I’m going to assume you’re already familiar with PHP and setting up a basic web app.

Also, I’m assuming you’ve got some basic familiarity with the command line, as I’m going to be making use of the very fantastic PHP package manager, composer

Composer

Composer is, in a nutshell, a way of easily installing PHP code into your application without the headache of manually including external libraries with all their dependencies.

For a quick intro and installation guide for Composer, click here. That’ll get you up and running.

Convert HTML To PDF

To install the library I’m using to convert HTML into PDF, DomPDF, run the following composer command from your project root:

composer require dompdf/dompdf

That’ll install all the required libraries I need to run DomPDF from within my simple little PHP app.

All I’ll be doing here is reading in the contents of my external HTML file, sample.html placed within the same directory as my project files.

Then, using DOMPDF’s own internal functionality, stream the generated file to the user’s browser, ready for downloading.

Here’s the code:

<?php
require_once('vendor/autoload.php');

// reference the Dompdf namespace
use DompdfDompdf;

$dompdf = new Dompdf();
// Enable the HTML5 parser to tolerate poorly formed HTML
$dompdf->set_option('isHtml5ParserEnabled', true);

// Load into DomPDF from the external HTML file
$content = file_get_contents('sample.html');

$dompdf->loadHtml($content);

// Render and download
$dompdf->render();
$dompdf->stream();

And the output, a downloadable PDF.

Generated PDF from DomPDF output

The result of running DomPDF on a chunk of HTML

Try it yourself:

Generate & Download PDF

You can also generate PDF documents from whole web pages — as long as you can grab a source of HTML, for example by using the PHP function file_get_contents, you can convert any accessible web page into PDF.

Convert HTML To Word

Although it’s a more archaic and less widely supported format, Microsoft Word documents remain a popular choice for saving/reading/printing documentation.

For this I’ll be using a different composer package, PHPWord. The approach is somewhat different than for generating PDFs.

First, install the package with composer.

composer require phpoffice/phpword

To get started, what’s happening in the following chunk of code is that I’m grabbing the HTML directly from the file sample.html and placing it within a DOMDocument object.

DOMDocument is a PHP class which allows for manipulation and extraction of data from HTML. Using this, it’s possible to search within HTML documents for specific pieces of data by attributes like id or class, or even by tag name — in much the same way that CSS selectors or Javascript DOM operations work.

Here, I’m getting a hold of the main page title, and the body content using the id attributes set within the HTML. You’ll see why shortly.

require_once('vendor/autoload.php');

$data = file_get_contents('sample.html');
$dom = new DOMDocument();
$dom->loadHTML($data);

// Now, extract the content I want to insert into my docx template

// 1 - The page title
$documentTitle = $dom->getElementById('title')->nodeValue;

// 2 - The article body content
$documentContent = $dom->getElementById('content')->nodeValue;

In the next step, I’m going to make use of an existing Word document to structure and template my generated document.

Now, unlike with DOMPDF, I can’t just take an HTML file and dump it straight into a Word document fully styled using PHPWord. It just doesn’t seem to work like that.

The approach I’m going to take is to use a template Word document, sample.docx and replace the title and content areas within that document with appropriate content from my HTML file (which I grabbed above using the getElementById method)

First, take a look at the file sample.docx in Word. You’ll see that it’s very sparse, with only a few bits of text, ${title}, ${author} and ${content}. These single words, surrounded by brackets and starting with a dollar symbol $ are the placeholders I’m going to use to swap out and replace with my HTML content.

PHPWord will be using this template document to construct my final document using the data I pass it.

Word template

The following lines are responsible for inserting that content into the Word template document.

// Load the template processor
$templateProcessor = new PhpOfficePhpWordTemplateProcessor('template.docx');

// Swap out my variables for the HTML content
$templateProcessor->setValue('author', "Robin Metcalfe");
$templateProcessor->setValue('title', $documentTitle);
$templateProcessor->setValue('content', $documentContent);

Using this approach, you can create a Word template styled as you require, complete with formatting, font styles, spacing etc. — Then you can drop content straight into that template from an HTML file.

This is only a simple example, but you can use more complex methods to copy segments of the template, remove segments and more. Take a look at the PHPWord class definition file to see what methods are available.

Finally, I prepare my headers to download the generated file, and stream the data to the user’s browser.

header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="generated.docx"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$templateProcessor->saveAs("php://output");

Generated PDF from DomPDF output

The result of running PHPWord on a chunk of HTML.

Note, though, the lack of any paragraph spacing or additional styling. You’d need to apply additional styling rules to the PHPWord object itself in order to more fully control the output of the script.

PHPWord by itself won’t parse any CSS included within the HTML file.

Try it yourself:

Generate & Download HTML » Word

If you’re looking for more examples on how to use PHPWord, I wouldn’t recommend the official documentation, it’s fairly sparse and still needs a lot of work.

Instead, take a look inside the /vendor directory after installing PHPWord using composer, specifically in phpoffice/phpword/samples where you’ll find a load of example files covering a range of use cases.

Convert HTML To Excel

One of the most useful conversions I’ve used before, is to produce Excel sheets using PHP, sometimes directly from HTML, but also straight from PHP using code.

In one instance, a client wanted to be able to download a spreadsheet of sales and performance metrics directly as an Excel sheet. No such functionality existed within the system, so I wrote some custom code for it using this technique.

Here’s a very quick example of how you can generate a simple spreadsheet using values provided in PHP.

Let’s get started. As before, I’ll install my dependencies using Composer:

composer require phpoffice/phpexcel

Now, for the content of my PHP file. This one is a fairly basic example, and the result is a few cells in a single sheet populated with numbers. Nothing too fancy.

require_once('vendor/autoload.php');

/**
 * Step 1: Setup
 */

$objPHPExcel = new PHPExcel();

$objPHPExcel->getProperties()->setCreator("Robin Metcalfe")
                             ->setLastModifiedBy("Robin Metcalfe")
                             ->setTitle("Excel test")
                             ->setSubject("Solarise Design")
                             ->setDescription("A test document for outputting an Excel file with some basic values.")
                             ->setKeywords("office PHPExcel php")
                             ->setCategory("Test result file");

$sheet = $objPHPExcel->setActiveSheetIndex(0);

/**
 * Step 2: Setting the values
 */

// row 1
$sheet->setCellValue("A1", 'Column A');
$sheet->setCellValue("B1", 'Column B');

// row 2
$sheet->setCellValue("A2", '1');
$sheet->setCellValue("B2", '2');

// row 3
$sheet->setCellValue("A3", '3');
$sheet->setCellValue("B3", '4');

/**
 * Step 3: Output
 */
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="html-to-excel.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

Although containing quite a few lines of code, there’s only three significant things happening here:

  • Creation of a new PHPExcel object, and some configuration work to add title, creator etc.
  • Setting the values of the cells within the Excel sheet
  • Output of the generated file to the user’s browser, along with some useful headers

See the result yourself,

Generate & Download Simple Excel File

A more complex example

But, to expand on the above, let’s explore how I can take data from an HTML file and convert that into Excel format.

Here, I’m going to extract all visible tables within the HTML file, then use that data to create an Excel file containing two seperate sheets.

The effect of this will be that the script will locate all table data within a page, and convert it into an Excel file, with one sheet per table

Neat, huh?

Generated Excel from PHPExcel output

The result of running PHPExcel on a chunk of HTML

I’m also going to be making use of the PHP class DomDocument to extract the required data from my HTML file as I did before with HTML to Word

In the following chunk of code, I do the following:

  • First, grab the required data from my sample HTML file
  • Then I extract the data I want from the <table> element within the HTML file, looping through the rows contained in <tbody>, and grabbing the column headers from the <thead> element.
  • Next, I loop through the data generated in the previous step, and insert this into my PHPExcel object, which will build up the structure of the Excel file
  • Finally, I output the generated Excel file to the user’s browser.

PHPExcel offers a range of additional methods and options to control styling, formatting and much more. Take a look through the class documentation and the samples within the vendor/phpoffice/phpexcel/Examples directory to find out more.

Generate & Download HTML » Excel

Here’s the code in full:

require_once('vendor/autoload.php');

// Pull in the HTML contents, and convert to XML
$data = file_get_contents('sample.html');

try {

    $dom = new DOMDocument();
    $dom->loadHTML( $data );

    // Get all tables in the document
    $tables = $dom->getElementsByTagName('table');

    // The array I'll store the table data in
    $tableData = array();

    foreach($tables as $tableN => $table) {
        // This requires properly formatted HTML table structure
        $head = $table->getElementsByTagName('thead')[0];
        $body = $table->getElementsByTagName('tbody')[0];

        // Table heading - assuming there is a heading directly before the table
        $tableData[] = array(
            'heading' => 'Table '.($tableN+1),
            'tableData' => array()
        );

        if($head && $body) {

            foreach($head->getElementsByTagName('tr')[0]->getElementsByTagName('th') as $colN => $headCell) {
                $tableData[$tableN]['tableData']['headings'][] = $headCell->nodeValue;
            }

            foreach($body->getElementsByTagName('tr') as $rowN => $tableRow) {
                foreach($tableRow->getElementsByTagName('td') as $colN => $tableCell) {
                    $tableData[$tableN]['tableData']['rows'][$rowN][$colN] = $tableCell->nodeValue;
                }
            }

        }

    }

} catch(Exception $e) {
    // I failed...
    exit;
}

// Instantiate the PHPExcel object
$objPHPExcel = new PHPExcel();

$objPHPExcel->getProperties()->setCreator("Robin Metcalfe")
                             ->setLastModifiedBy("Robin Metcalfe")
                             ->setTitle("HTML Tables To Excel Test")
                             ->setSubject("Solarise Design")
                             ->setDescription("A test document for converting HTML tables into Excel.")
                             ->setKeywords("office PHPExcel php")
                             ->setCategory("Test result file");

$alphabet = range('A', 'Z');

foreach($tableData as $tableN => $data) {

    if($tableN > 0) {
        $objPHPExcel->createSheet($tableN);
    }

    $sheet = $objPHPExcel->setActiveSheetIndex($tableN);
    $objPHPExcel->getActiveSheet()->setTitle($data['heading']);

    foreach($data['tableData']['headings'] as $n => $heading) {
        $sheet->setCellValue("{$alphabet[$n]}1", $heading);
    }

    foreach($data['tableData']['rows'] as $rowN => $rowData) {
        foreach($rowData as $colN => $value) {
            $n = $rowN + 2;
            $sheet->setCellValue("{$alphabet[$colN]}{$n}", $value);
        }       

    }

}

// Resize columns to fit data, just to tidy things up
foreach(range('A','Z') as $columnID) {
    $objPHPExcel
        ->getActiveSheet()
        ->getColumnDimension($columnID)
        ->setAutoSize(true);
}

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="html-to-excel.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

Download Source Code

To get a copy of all files used within this article, download them here.

Once downloaded, you’ll need to run composer install to setup all the dependencies.

Robin Metcalfe is a web developer specialising in WordPress development, Javascript and custom coding. He enjoys coffee, more coffee and music. Get in touch with any enquiries.

Join the discussion…

Excel is among the most used file types to export your website data, so in this tutorial I will show you how to export html to excel using php. It’s not that hard I will give you the main class of this functionality, then you only need to call the function and provide the required data to construct the table of the excel and that’s it. All the hard work is done by using this class, in the below code you will find all necessary functions to create an excel file with your custom data. Besides this class you will need to construct your data in a special way so the excel to be generated but I will show you how your arrays should look like.

<?php
/**
 * Simple excel writer class with no external dependencies, drop it in and have fun
 * @author Matt Nowack
 * @link https://gist.github.com/ihumanable/929039/edit
 * @license Unlicensed
 * @version 1.0
 */
class Excel {
  private $col;
  private $row;
  private $data;
  private $title;
  /**
   * Safely encode a string for use as a filename
   * @param string $title The title to use for the file
   * @return string The file safe title
   */
  static function filename($title) {
    $result = strtolower(trim($title));
    $result = str_replace("'", '', $result);
    $result = preg_replace('#[^a-z0-9_]+#', '-', $result);
    $result = preg_replace('#-{2,}#', '-', $result);
    return preg_replace('#(^-+|-+$)#D', '', $result);
  }
  /**
   * Builds a new Excel Spreadsheet object
   * @return Excel The Spreadsheet
   */
  function __construct($title) {
    $this->title = $title;
    $this->col = 0;
    $this->row = 0;
    $this->data = '';
    $this->bofMarker();
  }
  /**
   * Transmits the proper headers to cause a download to occur and to identify the file properly
   * @return nothing
   */
  function headers() {
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Disposition: attachment;filename=" . Excel::filename($this->title) . ".xls ");
    header("Content-Transfer-Encoding: binary ");
  }
  function send() {
    $this->eofMarker();
    $this->headers();
    echo $this->data;
  }
  /**
   * Writes the Excel Beginning of File marker
   * @see pack()
   * @return nothing
   */
  private function bofMarker() { 
    $this->data .= pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);  
  }
  /**
   * Writes the Excel End of File marker
   * @see pack()
   * @return nothing
   */
  private function eofMarker() { 
    $this->data .= pack("ss", 0x0A, 0x00); 
  }
  /**
   * Moves internal cursor left by the amount specified
   * @param optional integer $amount The amount to move left by, defaults to 1
   * @return integer The current column after the move
   */
  function left($amount = 1) {
    $this->col -= $amount;
    if($this->col < 0) {
      $this->col = 0;
    }
    return $this->col;
  }
  /**
   * Moves internal cursor right by the amount specified
   * @param optional integer $amount The amount to move right by, defaults to 1
   * @return integer The current column after the move
   */
  function right($amount = 1) {
    $this->col += $amount;
    return $this->col;
  }
  /**
   * Moves internal cursor up by amount
   * @param optional integer $amount The amount to move up by, defaults to 1
   * @return integer The current row after the move
   */  
  function up($amount = 1) {
    $this->row -= $amount;
    if($this->row < 0) {
      $this->row = 0;
    }
    return $this->row;
  }
  /**
   * Moves internal cursor down by amount
   * @param optional integer $amount The amount to move down by, defaults to 1
   * @return integer The current row after the move
   */
  function down($amount = 1) {
    $this->row += $amount;
    return $this->row;
  }
  /**
   * Moves internal cursor to the top of the page, row = 0
   * @return nothing
   */
  function top() {
    $this->row = 0;
  }
  /**
   * Moves internal cursor all the way left, col = 0
   * @return nothing
   */
  function home($col) {
    if(empty($col)){
    $this->col = 0;
  }
  else{
    $this->col = $col;
  }
  }
  /**
   * Writes a number to the Excel Spreadsheet
   * @see pack()
   * @param integer $value The value to write out
   * @return nothing
   */
  function number($value) { 
    $this->data .= pack("sssss", 0x203, 14, $this->row, $this->col, 0x0); 
    $this->data .= pack("d", $value); 
  }
  /**
   * Writes a string (or label) to the Excel Spreadsheet
   * @see pack()
   * @param string $value The value to write out
   * @return nothing
   */
  function label($value) { 
    $length = strlen($value);
    $this->data .= pack("ssssss", 0x204, 8 + $length, $this->row, $this->col, 0x0, $length); 
    $this->data .= $value; 
  }
}

This is the main class you will all the time to use in order to generate excel files. Now just copy paste the code in a file and upload to your server. Now we need to create a function which will send the data to this function to download the file later. In the below example you will see I am using $wpdb, I am using this because I am using wordpress to get the data I need to put in the excel, but this class can be used in any framework or cms. 

public function export_to_excel($fid){
    global $wpdb;
    $fid = intval($fid);
    $form_title = 'Excel';
    $data = $this->getFieldsByFormId($fid);	
    if(!empty($data)){
      //Check that the class exists before trying to use it
      $arrHeader = array();
      foreach($data[0] as $k => $v){
        $arrHeader[] = $k;
      }
      if(!class_exists('Excel')){
        //Include excel class file 
        require_once(dirname(__FILE__).'/inc/Excel.class.php');
        //create excel class object
        $xls = new Excel($form_title);
        $i=0;
        foreach($arrHeader as $colName ){
          $xls->home($i);
          $xls->label($colName);
          $i++;
        }
        foreach ($data as $k => $v){
          $i=0;	
          $xls->down();
          foreach ($v as $k2 => $v2){
            $colVal = ((isset($v[$k2])) ? htmlspecialchars_decode($v[$k2]) : '');
            $xls->home($i);
            $xls->label($colVal);
            $i++;
          }
        }
        $xls->send();
        exit;
      }
    }
  }

As you can see in the above function first time I get all fields I need then, first I create the header of the table represented by the arrHeader array then I pass all the data after I check if the class Excel exists. Using the xls->send() it will create the excel then it will be auto downloaded by the browser. Is quite simple to implement this functionality and and it is very helpful. However if you need an even easier method to export your data you can follow this tutorial where I show you how to export html table in csv using jquery. I hope you this tutorial will help you to achive this functionality, let me know in the comments section.

If you are willing to learn how can we generate excel file by using jquery, so this is the right place in which I will learn you how to use jquery with php programming for export of html table data to Excel file. This is my short PHP web development tutorial in which We will talk about how we can use jquery code for export html table data to excel file format by using PHP. In number of web pages in your web application, you want to give one option for generate excel file from your html data table. With the help of this clean php code execute with the help jquery. You can efficiently build the functionality like export any type of html table data to excel file format by using php programming with Jquery. In this PHP web development tutorial first I will fetch data from mysql table and display that table data on the web page in html table and below html table I have put one button for export html table data to excel file. When user click on that button html data will be exported to excel file. I will jquery code on button click event. This code is working on most of the modern browser like a Old and New Internet Explorer, Google Chrome Fire Fox etc. I wish you have something learn from this post.

Export HTML table to Excel File using Jquery with PHP

Source Code

Database

 --  
 -- Table structure for table `tbl_employee`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_employee` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(50) NOT NULL,  
  `gender` varchar(10) NOT NULL,  
  `designation` varchar(100) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=22 ;  
 --  
 -- Dumping data for table `tbl_employee`  
 --  
 INSERT INTO `tbl_employee` (`id`, `name`, `gender`, `designation`) VALUES  
 (1, 'Bruce Tom', 'Male', 'Driver'),  
 (5, 'Clara Gilliam', 'Female', 'Programmer'),  
 (6, 'Barbra K. Hurley', 'Female', 'Service technician'),  
 (7, 'Antonio J. Forbes', 'Male', 'Faller'),  
 (8, 'Charles D. Horst', 'Male', 'Financial investigator'),  
 (9, 'Beau L. Clayton', 'Male', 'Extractive metallurgical engin'),  
 (10, 'Ramona W. Burns', 'Female', 'Electronic typesetting machine operator'),  
 (11, 'Jennifer A. Morrison', 'Female', 'Rigging chaser'),  
 (12, 'Susan M. Juarez', 'Female', 'Control and valve installer'),  
 (13, 'Ellan D. Downie', 'Female', 'Education and training manager'),  
 (14, 'Larry T. Williamson', 'Male', 'Teaching assistant'),  
 (15, 'Lauren M. Reynolds', 'Female', 'Internet developer'),  
 (16, 'Joseph L. Judge', 'Male', 'Refrigeration mechanic'),  
 (17, 'Eric C. Lavelle', 'Male', 'Model'),  
 (18, 'Cheryl T. Smithers', 'Female', 'Personal banker'),  
 (19, 'Tonia J. Diaz', 'Female', 'Facilitator'),  
 (20, 'Stephanie P. Lederman', 'Female', 'Mental health aide'),  
 (21, 'Edward F. Sanchez', 'Male', 'Marine oiler');  

index.php

 <?php   
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 $query = "SELECT * FROM tbl_employee";  
 $result = mysqli_query($connect, $query);  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Export HTML table to Excel File using Jquery with PHP</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:700px;">  
                <h3 class="text-center">Export HTML table to Excel File using Jquery with PHP</h3><br />  
                <div class="table-responsive" id="employee_table">  
                     <table class="table table-bordered">  
                          <tr>  
                               <th width="10%">Id</th>  
                               <th width="30%">Name</th>  
                               <th width="10%">Gender</th>  
                               <th width="50%">Designation</th>  
                          </tr>  
                          <?php   
                          while($row = mysqli_fetch_array($result))  
                          {  
                          ?>  
                          <tr>  
                               <td><?php echo $row['id']; ?></td>  
                               <td><?php echo $row['name']; ?></td>  
                               <td><?php echo $row['gender']; ?></td>  
                               <td><?php echo $row['designation']; ?></td>  
                          </tr>  
                          <?php                           
                          }  
                          ?>  
                     </table>  
                </div>  
                <div align="center">  
                     <button name="create_excel" id="create_excel" class="btn btn-success">Create Excel File</button>  
                </div>  
           </div>  
           <br />  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#create_excel').click(function(){  
           var excel_data = $('#employee_table').html();  
           var page = "excel.php?data=" + excel_data;  
           window.location = page;  
      });  
 });  
 </script>  

excel.php

 <?php  
 //excel.php  
 header('Content-Type: application/vnd.ms-excel');  
 header('Content-disposition: attachment; filename='.rand().'.xls');  
 echo $_GET["data"];  
 ?>  

Like this post? Please share to your friends:
  • Php excel from array
  • Php excel and mysql
  • Php data import from excel
  • Php csv для excel
  • Php csv for excel