To begin, create a button and add the event on click to trigger it.
The link can be something like this:
<a href='#' OnClick='GenerateExcel()'>Export to Excel</a>
The GenerateExcel is the vbscript which you can define as follows:
<SCRIPT LANGUAGE="VBScript">
Sub GenerateExcel()
On Error Resume Next
...
End Sub
</SCRIPT>
Next is to create a excel object as follows:
Assuming that you are populating from a resultset, you can then start looping through the result set as follows:
Set Excel = CreateObject("Excel.Application")
Set ExcelWBk = Excel.Workbooks.Add
Set ExcelWS = ExcelWBk.Worksheets(1)
Excel.visible = True
ExcelWS.name = "Data"
Some additional that can be done is to check on the number of rows in the Result set before looping.
<%
row = 2
oRs.MoveFirst
' --------------------------
For i = 0 To oRs.Fields.Count - 1 %>
ExcelWS.Cells(1, <% =(i + 1) %>) = "<% =oRs.Fields(i).Name %>"
<% Next
' --------------------------
Do While Not oRs.EOF
For i = 0 To oRs.Fields.Count - 1 %>
' ExcelWS.Cells(1, <% =(i + 1) %>) = "<% =oRs.Fields(i).Name %>"
ExcelWS.Cells(<% =row %>, <% =(i + 1) %>) = "<% =oRs.Fields(i).Value %>"
<% Next
row = row + 1
oRs.MoveNext
Loop
%>
This approach has many flaws and such as:
- It only runs on Windows and in IE with excel installed.
- You need to open up the security in your IE to allow executing of unsigned script (recommended to set it to prompt).
- It will create a huge script on the browser (so will use memory on the client).
- It will generate the script irrespecive if the script is used again.
No comments:
Post a Comment