01.
<html>
02.
<head>
03.
<title>ThaiCreate.Com PHP(COM) Excel.Application Tutorial</title>
04.
</head>
05.
<body>
06.
<?
07.
$objConnect
= mysql_connect(
"localhost"
,
"root"
,
"root"
)
or
die
(
"Error Connect to Database"
);
08.
$objDB
= mysql_select_db(
"mydatabase"
);
09.
$strSQL
=
"SELECT * FROM customer"
;
10.
$objQuery
= mysql_query(
$strSQL
);
11.
if
(
$objQuery
)
12.
{
13.
14.
$strPath
=
realpath
(
basename
(
getenv
(
$_SERVER
[
"SCRIPT_NAME"
])));
15.
16.
17.
$strFileName
=
"MyXls/MyExcel.xls"
;
18.
19.
20.
$xlApp
=
new
COM(
"Excel.Application"
);
21.
$xlBook
=
$xlApp
->Workbooks->Add();
22.
23.
24.
25.
$xlBook
->Worksheets(1)->Name =
"My Customer"
;
26.
$xlBook
->Worksheets(1)->Select;
27.
28.
29.
$xlApp
->ActiveSheet->Cells(1,1)->Value =
"CustomerID"
;
30.
$xlApp
->ActiveSheet->Cells(1,2)->Value =
"Name"
;
31.
$xlApp
->ActiveSheet->Cells(1,3)->Value =
"Email"
;
32.
$xlApp
->ActiveSheet->Cells(1,4)->Value =
"CountryCode"
;
33.
$xlApp
->ActiveSheet->Cells(1,5)->Value =
"Budget"
;
34.
$xlApp
->ActiveSheet->Cells(1,6)->Value =
"Used"
;
35.
36.
37.
$intRows
= 2;
38.
while
(
$objResult
= mysql_fetch_array(
$objQuery
))
39.
{
40.
41.
$xlApp
->ActiveSheet->Cells(
$intRows
,1)->Value =
$objResult
[
"CustomerID"
];
42.
$xlApp
->ActiveSheet->Cells(
$intRows
,2)->Value =
$objResult
[
"Name"
];
43.
$xlApp
->ActiveSheet->Cells(
$intRows
,3)->Value =
$objResult
[
"Email"
];
44.
$xlApp
->ActiveSheet->Cells(
$intRows
,4)->Value =
$objResult
[
"CountryCode"
];
45.
$xlApp
->ActiveSheet->Cells(
$intRows
,5)->Value =
$objResult
[
"Budget"
];
46.
$xlApp
->ActiveSheet->Cells(
$intRows
,6)->Value =
$objResult
[
"Used"
];
47.
$intRows
++;
48.
}
49.
50.
@unlink(
$strFileName
);
51.
52.
$xlBook
->SaveAs(
$strPath
.
"/"
.
$strFileName
);
53.
54.
55.
56.
$xlApp
->Application->Quit();
57.
$xlApp
= null;
58.
$xlBook
= null;
59.
$xlSheet1
= null;
60.
61.
}
62.
63.
mysql_close(
$objConnect
);
64.
?>
65.
Excel Created <a href=
"<?=$strFileName?>"
>Click here</a> to Download.
66.
</body>
67.
</html>