Rodrigo Régis

Tag: excel

Exportar para excel com PHP

by Rodrigo Régis Palmeira on jul.09, 2009, under PHP

Olá
Hoje vou postar um método muito interessante (e que pouca gente sabe) para exportar seu conteúdo HTML para uma planilha em excel (.xls).

Trata-se apenas de forçar o download do arquivo através da função header() que é nativa do PHP.

Coloquei a function como método estático dentro de uma classe (Util.php) para que a coleção de funções de uso geral fiquem mais organizadas e acessíveis.

Segue o método:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
class Util
{
	/**
	 * @author Rodrigo Régis Palmeira
	 * @link http://www.rodrigoregis.com.br
	 * @param string $html
	 * @return file.xls
	 */
	public static function toXLS($html)
	{
		header("Content-type: application/vnd.ms-excel");
		header("Content-type: application/force-download");
		header("Content-Disposition: attachment; filename=file.xls");
		header("Pragma: no-cache");
		echo $html;
		exit();
	}
}
?>

Agora veja como é fácil a aplicação:

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
27
28
29
<?php
$html = <<<HTML
<table width='90%' border='1'>
	<tr>
		<th>Título </th>
		<th>Título 2</th>
		<th>Título 3</th>
	</tr>
	<tr>
		<td>Dados 1</td>
		<td>Dados 2</td>
		<td>Dados 3</td>
	</tr>
	<tr>
		<td>Dados 4</td>
		<td>Dados 5</td>
		<td>Dados 6</td>
	</tr>
	<tr>
		<td>Dados 7</td>
		<td>Dados 8</td>
		<td>Dados 9</td>
	</tr>
</table>
HTML;
 
//Chamando o método
Util::toXLS($html);
?>

Por hoje é só!

Espero ter ajudado!

2 Comments :, , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

Archives

All entries, chronologically...