ASP กับ Microsoft Excel
สำหรับการส่งข้อมูลออกในรูปแบบของ Microsoft Excel สามารถทำได้ 2 วิธีครับ
1.การส่ง Header ให้เป็นในรูปแบบของ Microsoft Excel ซึ่งจะต้อง ใช้ความสามารถของเครื่องฝั่ง Client ในการเปิด Excel
2.การสร้างไฟล์ Excel โดยอาศัย COM ของฝั่ง Server ซึ่งฝั่ง Server จะต้องทำการติดตั้ง Excel.Application
โดยจะต้องทำการติดตั้ง Microsoft Office
มาดูตัวอย่างกันหน่อยนะครับ
วิธีที่ 1
การส่ง Header ให้เป็นในรูปแบบของ Microsoft Excel ซึ่งจะต้อง ใช้ความสามารถของเครื่องฝั่ง Client ในการเปิด Excel
Sample1.asp
<%
Response.ContentType = "application/vnd.ms-excel"
%>
<table width="30%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
วิธีที่ 2
การสร้างไฟล์ Excel โดยอาศัย COM ของฝั่ง Server ซึ่งฝั่ง Server จะต้องทำการติดตั้ง Excel.Application
โดยจะต้องทำการติดตั้ง Microsoft Office
Sample2.asp
<%
Set xlApp = Server.CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
xlApp.Application.Visible = False
With xlApp.ActiveSheet.Cells(1,1)
.Value = "Overall Product Sales 2000"
.Font.Bold = True
.Font.Name = "Tahoma"
.Font.Size = 16
End With
With xlApp.ActiveSheet.Cells(3,1)
.Value = "Product Name"
.Font.Italic = True
.Font.Name = "Tahoma"
.Font.Size = 13
.MergeCells = True
End With
With xlApp.ActiveSheet.Cells(3,2)
.Value = "Product Income"
.Font.Italic = True
.Font.Name = "Tahoma"
.Font.Size = 13
.MergeCells = True
End With
Set objConn = Server.CreateObject("ADODB.Connection")
Set objRS = Server.CreateObject("ADODB.Recordset")
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
strConn = strConn & Server.MapPath("Sales00.mdb")
strQuery = "SELECT ProductName,ProductIncome FROM ProductSales"
While Not objRS.EOF
xlApp.ActiveSheet.Cells(iRow,1).Value = objRS("ProductName")
xlApp.ActiveSheet.Cells(iRow,2).Value = objRS("ProductIncome")
xlApp.ActiveSheet.Cells(iRow,2).NumberFormat = "$#,##0.00"
iRow = iRow + 1
objRS.MoveNext
Wend
xlSheet.SaveAs Server.MapPath("MyExcelBook.xls")
xlApp.Application.Quit
objRS.Close
objConn.Close
Set objRS = Nothing
Set objConn = Nothing
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
|