Posted on

Creating Excel sheets with HTML tables

xls-sheet-03

Sometimes it is pretty handy to create an HTML table containing all your information and just open it with Excel. Usually the main issue is the formatting within Excel – you want to have it Define the header

Define the header to have a usefule name for your Excel file. This is pretty nice if you need to save these files later on and do not want to enter the filename manually all the time.

header('Content-Type: application/msexcel;charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$date.'_'.$_REQUEST['type'].'-Export.xls"');

Define the cell type

It is possible to define the kind of information within each cell. This is simply done by assigning a proper CSS class to your TD element. Here some simple examples:

.xls-number {
	mso-number-format:"0"
} 
.xls-number-2dec {
	mso-number-format:"0\.00"
} 
.xls-text {
	mso-number-format:"\@"
} 
.xls-text-nowrap {
	mso-number-format:"\@";
	white-space:nowrap;
} 

And now you can use it in your table:

<table>
<tr>
	<td class="xls-number">1</td>
	<td class="xls-number-2dec">100.00</td>
	<td class="xls-text">Title</td>
	<td class="xls-text-nowrap">A lot of text but we do not want to break the cell.</td>
</tr>
</table>

More information

Here a great link with additional formatting options:
XLS formatting