How to export html table to excel or pdf in php
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..
Solution 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
Solution 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.
Solution 3:
Use a PHP Excel for generatingExcel file. You can find a good one called PHPExcel here: https://github.com/PHPOffice/PHPExcel
And for PDF
generation use http://princexml.com/