You Are Here: Home » How-To » Programming

How To Easily Create / Generate MS Excel Files Using PHP [Just 2 Lines]

By Debjit on May 16th, 2011 
Advertisement

In this article we will tell you how to easily generate MS Excel files using PHP and without the use of any bulky third party code libraries. The idea behind this method is to set the content-type and the content-disposition properties in the header function of PHP to values that produce MS Excel as output. And the data which you want to be filled in your Excel sheet (file) can be simply printed as HTML tables in the script.

Here are the two lines of code in the script which we are talking about:

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=YOUR_FILE_NAME.xls");

The only thing you need to change in the above code snippet is replace YOUR_FILE_NAME with the desired filename you want to generate your excel file with. So, if you want to generate an excel sheet with three columns and two rows, just put the above two lines of code at the TOP of your PHP script, followed by an HTML table with three columns and two rows with the data you want in the excel sheet. Here is the code snippet:

<?php
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=testfile.xls");
echo "<table>";
echo "<tr>";
echo "<td>Data One</td><td>Data Two</td><td>Data Three</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Data Four</td><td>Data Five</td><td>Data Six</td>";
echo "</tr>";
echo "</table>";
?>

 

Advertisement







How To Easily Create / Generate MS Excel Files Using PHP [Just 2 Lines] was originally published on Digitizor.com on May 16, 2011 - 4:25 am (Indian Standard Time)