2010年5月11日 星期二

簡易 php Excel Export Function.

簡易 php Excel Export Function.

<?php

function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}

function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}

function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
return;
}

function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}

$fileName=time();
// Query Database

mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");
// Send Header
///*
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=$fileName.xls");
header("Content-Transfer-Encoding: binary ");
//*/
// XLS Data Cell

xlsBOF();

xlsWriteLabel(1,0,"Student Register $fileName");
xlsWriteLabel(2,0,"COURSENO : ");
xlsWriteLabel(2,1,"$fileName");
xlsWriteLabel(3,0,"TITLE : ");
xlsWriteLabel(3,1,"$title");
xlsWriteLabel(4,0,"SETION : ");
xlsWriteLabel(4,1,"$fileName");

xlsWriteLabel(6,0,"NO");
xlsWriteLabel(6,1,"ID");
xlsWriteLabel(6,2,"Name");
xlsWriteLabel(6,3,"title");
xlsWriteLabel(6,4,"sex");

$xlsRow = 7;
while($row = mysql_fetch_assoc($result)){
++$i;

xlsWriteNumber($xlsRow,0,"$i");
xlsWriteNumber($xlsRow,1,"$row[PK]");
xlsWriteLabel($xlsRow,2,"$row[name]");
xlsWriteLabel($xlsRow,3,"$row[title]");
xlsWriteLabel($xlsRow,4,"$row[sex]");
$xlsRow++;

}

xlsEOF();
exit();

?>

【下列文章您可能也有興趣】

沒有留言: