View Full Version : Create an Excel file from a search form
paulafernandes
12-30-2002, 05:00 PM
Hi!
I'm doing an aplication in a intranet enviroment.
In a certain point of the aplication, I do a search and I need to create an excel file with the result of that search.
Can anobody tell me how I do it or where can I find more information about it? I already look for but I can't find exactly what I want...
Thank's and happy new year to all of you!!!
Paula
brothercake
12-30-2002, 06:10 PM
I'd guess you can do it through COM, so ASP would probably have the functionality you need. I can't tell you much more I'm afraid, but http://msdn.microsoft.com/library/default.asp?url=/nhp/Default.asp?contentid=28000550 looks like a good place to start.
whammy
12-31-2002, 12:25 AM
You can actually create it using FileSystemObject, it's really simple if you just need the data... I actually use this method when I DON'T want to create a really complicated reporting script. ;)
http://www.w3schools.com/asp/asp_ref_filesystem.asp
Once you have run your query, you can just loop through each record and write it to a .txt file, but instead of naming the file .txt just name it .xls (or even .csv!). Then provide a link to the newly created file, and the user can download it (or open it in their browser) in Excel.
If you need more help with it, I have a working example I will post for you when I get a chance.
:D
brothercake
12-31-2002, 12:29 AM
Originally posted by whammy
you can just loop through each record and write it to a .txt file, but instead of naming the file .txt just name it .xls (or even .csv!). Then provide a link to the newly created file, and the user can download it (or open it in their browser) in Excel.
Aha ... so you use the fact that a delimited text file called .xls will open as a spreadsheet ... cunning ;)
whammy
12-31-2002, 12:31 AM
Exactly - wish I had thought of it myself. ;)
Luckily I learned that little trick of renaming the file from another developer I work with (and I am sure they learned it from somewhere else, probably a website somewhere, or accidentally opening a comma-delimited text file saved as a .csv with Excel since it may have been the default program to open the .csv extension in their OS - it's funny how you pick up things like that on accident sometimes, when you work with different companies and data files!).
Little things like this can sure make your life easier, though! :)
whammy
12-31-2002, 02:23 PM
Here's an example:
<%
Dim fs, f, thefile, Conn, dbquery, rs, linevalue, LeadColumns
thefile = Server.MapPath("yourfilename.csv")
Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile(thefile, 2, True)
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open 'Put your connection string here
Set rs = Server.CreateObject("ADODB.Recordset")
dbquery = "SELECT * FROM tablename ORDER BY whatever"
Set rs = Conn.Execute(dbquery)
For Each Item in rs.fields
LeadColumns = LeadColumns & """" & Replace(Item.Name,"""","") & ""","
Next
LeadColumns = Left(LeadColumns,Len(LeadColumns)-1)
f.WriteLine(LeadColumns)
Do While NOT rs.EOF
linevalue = "" 'reset linevalue to empty
For Each Item in rs.fields
linevalue = linevalue & """" & Replace(Item.Value,"""","") & ""","
Next
linevalue = Left(linevalue,Len(linevalue)-1)
f.WriteLine(linevalue)
rs.MoveNext
Loop
Set rs = Nothing
Conn.Close
Set Conn = Nothing
Set f = Nothing
Set fs = Nothing
%>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
<head>
<title>Download/open the file</title>
</head>
<body>
<div>
<a href="yourfilename.csv">Click here</a> to download/open the file.
</div>
</body>
</html>
glenngv
01-02-2003, 06:52 AM
Another way without using FSO, just plain HTML :D
<%
response.contenttype="application/vnd.ms-excel"
%>
This is Cell A1-A1
<TABLE border="1">
<TR>
<TD>This is Cell A2-A1</TD>
<TD>This is Cell A2-B1</TD>
</TR>
<TR>
<TD>This is Cell A3-A1</TD>
<TD>This is Cell A3-B1</TD>
</TR>
</TABLE>
or if you want to save it as .csv file:
(Download dialog will be prompted)
<%
response.contenttype="application/csv"
Response.write "This is Cell A1-A1" & VbCrLf
Response.write "This is Cell A2-A1,This is Cell A2-B1" & VbCrLf
Response.write "This is Cell A3-A1,This is Cell A3-B1" & VbCrLf
%>
aCcodeMonkey
01-03-2003, 03:35 AM
Paula,
Below is code to dynamically create an XLS File. The file will be displayed on the end user's browser and they can save it to their system. There are even a few tips for formatting the data. Note this sample has predefined queries. In other versions of this code I pass the SQL statements via HTTPPost.
<%@ Language=VBScript %>
<% option explicit %>
<%
'Author: Dale A. Mitchell
'Company: MindCrafter Web Designs
'Created: 2/03/2001
'Modified: 9/24/2002
'Description: The following code allows for mulitple web data forms to generate XLS files for local access.
' The code will generate a simple Excel worksheet or can be used as the base for more complex output bu including Excel
' functions within individual data cells or by modifying the SQL statement accordingly.
'
'Associated Files: xls.gif; frmCreateXLS.htm
dim sSQL
' Check to see if the URL is correct
if isNumeric(Request.QueryString("FrmID")) then
' Set SQL Query Based ong the requesting web form id
select case CInt(Request.QueryString("FrmID"))
case 1
sSQL="SELECT FNAME, LNAME, TITLE, EMAIL, HomePhone, WorkPhone, Comments " & _
"FROM Users " & _
"ORDER BY LNAME ASC"
case 2
sSQL="SELECT Contact, Business, Address, City, State, Country, TITLE, EMAIL, HomePhone, WorkPhone, Comments " & _
"FROM Bus_Contacts " & _
"ORDER BY LNAME ASC"
case 3
sSQL=""
end select
GenerateXLS
else
DisplayErrMessage 0
end if
sub GenerateXLS()
dim nField
dim oConn,oRs
set oRs = server.CreateObject("ADODB.RECORDSET")
set oConn = server.createobject("ADODB.CONNECTION")
' Change to the correct connection string for your website
oConn.ConnectionString = Application("ReadOnly")
' If you get errors writing the XLS file set the buffer to false.
' This will allow the XLS file to open and display the ADO error.
Response.Buffer = TRUE
' Set the option to save the recordset as an XLS fiel.
' Note: The web user account cannot have write permissions on the directory where the file resides.
' If the web user account does have write permision, static html can be generated and passed to the client's browser.
' this is a known bug in IE and Excel.
Response.ContentType = "application/vnd.ms-excel"
oConn.open
oRs.Open sSQL,oConn,3,3
if oRs.EOF then ' Clean up ADO Objects and display error popup
oRs.Close
set oRs = nothing
oConn.Close
set oConn=nothing
DisplayErrMessage 1
else
' Create XLS File
' This code will dynamically create a table based on the number of fields returned by the SQL Query
Response.Write "<html><body>" & vbNewLine
Response.Write "<table border=" & chr(34) & "1" & chr(34) & " cellpadding=" & chr(34) & "0" & chr(34) & " cellspacing=" & chr(34) & "0" & chr(34) & "><tr>" & vbNewLine
' Create table "Header" cells
for nField = 0 to (oRs.Fields.count-1)
Response.Write "<td>" & oRs.Fields(nField).Name & "</td>"
next
Response.Write "</tr>" & vbNewLine
' Create data cells
' Formula example: <TD FORMULA="=Sum(A2:B2)">
' Number Formatting: <td STYLE="vnd.ms-excel.numberformat:$#.0000[semicolon]($#.0000)">
do until oRs.EOF
Response.Write "<tr>"
for nField = 0 to (oRs.Fields.count-1)
Response.Write "<td>" & oRs.Fields(nField).Value & "</td>"
next
Response.Write "</tr>" & vbNewLine
oRs.MoveNext
loop
Response.Write "</tr></table>" & vbNewLine
Response.Write "</body></html>" & vbNewLine
' Clean up ADO Objects
oRs.Close
set oRs = nothing
oConn.Close
set oConn=nothing
end if
end sub
sub DisplayErrMessage(nErrLvl)
dim sMsgText
select Case nErrLvl
case 0
sMsgText="Invalid Request!"
case 1
sMsgText="No data to display"
end select
' Note: The error message prompt does not have to be a javascript popup.
%>
<script language="javascript">
alert('<%= sMsgText %>')
window.close()
</script>
<%
Response.End
end sub
%>
Hope this helps. :cool:
glenngv
01-03-2003, 03:48 AM
aCcodeMonkey, same concept as mine :)
only you spoon-fed all the codes :D
paulafernandes
01-03-2003, 02:15 PM
Hi!
Thank's for all the help!
I used the code that whammy gave and It worked just like I wanted. Anyway, aCcodeMonkey, thank's!
I'm finishing this aplication and your help was precious. I'm starting a new aplication monday, so I guess I will need more of your help...
I just hope that someday I'll be such a good programmer like all of you!
Paula
whammy
01-04-2003, 12:59 AM
:cool:
Hey, don't worry, this ASP stuff is a cinch.
You'll be up to snuff in no time - you're already doing awesome coding from what I've seen!
Of course we're always learning, but this is the best place to be, at least for general web development knowledge. There are things I've learned here that you'd never learn on an "ASP only" or ".NET only" forum...
I learned another way to create an excel file just from this thread (of course I am always learning things from glenngv ;), and aCcodemonkey's post was also excellent, especially the formula example!).
aCcodeMonkey
01-04-2003, 03:04 AM
Didn't have much choice about learning the Excel tricks. Use to program management reports for Compaq.
Oh how those managers love Excel.....
:cool:
Leeus
01-04-2003, 10:05 AM
I had this problem, what I did was used Excel to design the sheet, outputted it to HTML. Did alot of cleaning up. Renamed the file to asp adn add in SQL statements and recordsets. See thishttp://www.hotscripts.com/ASP/Tips_and_Tutorials/Excel_and_ASP/ for some help.
Boxhead
01-16-2004, 10:52 AM
whammy
I have used your method of writing to a csv file and everything works fine. BUT...
I want to create a page when users can select which information they send to the csv page by ticking checkboxes. i have used an array to check for each check box in a url param - if the url param exists then it sets an array to 'export', if not to 'ignore'. I then use your code to to write each field name and value IF the array is set to export, but it doesn't work!! here is my code:
<%
Dim fieldArray(5), qsParam, qsArray(5)
fieldArray (0) = "title"
fieldArray (1) = "fore"
fieldArray (2) = "sur"
fieldArray (3) = "road"
fieldArray (4) = "town"
For i = 0 to UBound(fieldArray)-1
qsParam =""&fieldArray(i)&""
If Request.QueryString(qsParam) = "1" Then
qsArray(i) = "export"
Else
qsArray(i) = "ignore"
End If
Next
%>
<%
i=0
For Each Item in Recordset1.fields
If (qsArray(i) = "export") Then
LeadColumns = LeadColumns & """" & Replace(Item.Name,"""","") & ""","
End If
i=i+1
Next
LeadColumns = Left(LeadColumns,Len(LeadColumns)-1)
f.WriteLine(LeadColumns)
i=0
Do While NOT Recordset1.EOF
linevalue = "" 'reset linevalue to empty
For Each Item in Recordset1.fields
If (qsArray(1) = "export") Then
linevalue = linevalue & """" & Item.Value & ""","
End If
i=i+1
Next
linevalue = Left(linevalue,Len(linevalue)-1)
f.WriteLine(linevalue)
Recordset1.MoveNext
Loop
Recordset1.MoveFirst
%>
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.