04 Jan, 2009

Excel and PHP

Posted by: admin In: howto|php

From Office 97 version, the World famous spreadsheet can read html table’s like a spreadsheet rows and colums.
With this interesting feature we can create .xls file on the fly from php with a simple play of <table> html tag.

Here the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
    $filename="spreadsheet.xls";
    header ("Content-Type: application/vnd.ms-excel");
    header ("Content-Disposition: inline; filename=$filename");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My XLS title</title>
</head>
<body>
<table border="0">
<?
    for ($i=1;$i < 100; $i++)
    {
        echo "<tr>";
        for ($j=1; $j<100;$j++)
        {
            $a = $i * $j;
            echo "<td>$a</td>";
        }
        echo "</tr>";
    }
?>
</table>
</body></html>

With line 3 we exchange the html data to excel
With line 4 we download the file insted of open ino the browser

as you can see, you can play with the table and collect data from a database, for generate some .xls spreadsheet on the fly, with the data you want for specific user, or specific situations.

No Responses to "Excel and PHP"

Comment Form