Première version publique
[auf_paf.git] / php_excel.php
1 <?php
2
3 /**
4 * @author sapta
5 * @copyright 2009
6 */
7
8 $cdate = date("Y-m-d"); // get current date
9
10 // configuration
11 $mysql_host = 'localhost';
12 $mysql_user = 'root';
13 $mysql_pass = 'root';
14 $mysql_db = 'pafauf_bdd';
15 $query_string = "select * from v_excel";
16 $export_filename = "exported_tableau_on_$cdate.xls";
17
18 // connect to mysql server
19 $mysql_link = mysql_connect($mysql_host,$mysql_user,$mysql_pass);
20 mysql_select_db($mysql_db,$mysql_link);
21
22 // query from table
23 $result = mysql_query($query_string);
24
25 $count = mysql_num_fields($result);
26
27 // fetch table header
28 $header = '';
29 for ($i = 0; $i < $count; $i++){
30 $header .= mysql_field_name($result, $i)."\t";
31 }
32
33 // fetch data each row, store on tabular row data
34 while($row = mysql_fetch_row($result)){
35 $line = '';
36 foreach($row as $value){
37 if(!isset($value) || $value == ""){
38 $value = "\t";
39 }else{
40 # important to escape any quotes to preserve them in the data.
41 $value = str_replace('"', '""', $value);
42 # needed to encapsulate data in quotes because some data might be multi line.
43 # the good news is that numbers remain numbers in Excel even though quoted.
44 $value = '"' . $value . '"' . "\t";
45 }
46
47 $line .= $value;
48 }
49 $data .= trim($line)."\n";
50 }
51
52 # this line is needed because returns embedded in the data have "\r"
53 # and this looks like a "box character" in Excel
54 $data = str_replace("\r", "", $data);
55
56 # Nice to let someone know that the search came up empty.
57 # Otherwise only the column name headers will be output to Excel.
58 if ($data == "") {
59 $data = "\nno matching records found\n";
60 }
61
62 // create table header showing to download a xls (excel) file
63 header("Content-type: application/octet-stream");
64 header("Content-Disposition: attachment; filename=$export_filename");
65 header("Cache-Control: public");
66 header("Content-length: ".strlen($data)); // tells file size
67 header("Pragma: no-cache");
68 header("Expires: 0");
69
70 // output data
71 echo $header."\n".$data;
72
73 ?>