ASP read data EXCEL

   EXCEL as the database to read have a very strict format restrictions, there will be a lot of problems ...
'===================
' Ⅰ) will generate Excel97 or Excel2000 XLS file (book) as a database, in which each sheet (sheet) as the database table
'ⅱ) ADO is assumed that the first acts of the field names in Excel, so you define the scope of the first line must be included content
'ⅲ) in Excel header row (i.e., field name) can be without a number. Excel driver in the face of this problem, an error occurs. For example, your row heading called "F1"
'Ⅳ) If Excel column in a table contains both text and numbers, then Excel ODBC driver will not be able to properly handle data type this line, you must ensure that the column consistent with the data type (add default symbol turn forced into text, background and then disposed of)
'ⅴ) when the date type, the entire list with no spaces, or can not read
' =============== ============= Raiders: ===============
1, obtained by filefield file
2, file verification .xls
3, to establish a connection
'connection established excel
Server.CreateObject excelconn = SET ( "ADODB.Connection")
strAddr = the Server.MapPath (uploadpath & filename)
'output source file name Response.Write "source file:" & strAddr & ""
excelconn.open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & strAddr
     '建立excel记录集
set excelrs=server.createobject("adodb.recordset")
sql="select * from [Sheet1$]" excelrs.open sql,excelconn,1,1 ............   excelrs.close()
     set excelrs=nothing
     excelconn.Close()
set excelconn=nothing
================================
<%Option Explicit%>
<html>
<head>
<title>操纵Excel</title>
</head>
<body>
<h2 align="center">显示Excel文件示例</h2>
<table border="1" width="90%" align="center">
<tr align="Center "bgcolor =" # E6E6E6 "> </ TR>
<td> Student ID </ td> <td> Name </ td> <td> mathematics </ td> <td> Language </ td> <td> English </ td> <td> out </ TD>

<%
'Create Connection object
Dim DB, RS, strSql
the Set DB = Server.CreateObject ( "ADODB.Connection")
db.Open "the Microsoft Excel Driver Driver = {(* * .xls)}; Dbq =" & the Server.MapPath ( "Mark.xls")
'open record set, the table name must be in the format "[$ table name]" in
strSql = "* the From the Select [Sheet1 $]"
the set RS = db.Execute (strSql)
' loop to read all the line
the Do Not rs.EOF the While
Response.Write "<align = left = TR 'Center'>"
Response.Write "<TD>" & RS ( "student number") & "</ TD>"
Response.Write "<TD> "& rs (" name ") &" </ td> "
Response.Write" <td> "& rs (" math ") &" </ td> "
the Response.Write "<td>" & rs("语文") & "</td>"
Response.Write "<td>" & rs("英语") & "</td>"
Response.Write "<td>" & rs("总分") & "</td>"
Response.Write "</tr>"
rs.MoveNext
Loop
'关闭对象
rs.Close
Set rs=nothing
db.Close
Set db=Nothing
%>
</table>
</body>
</html>

 

 

 

 

<%
set rs=server.createobject("adodb.recordset")
sql="select * from provinceinfo where 1=1"
rs.open sql,objconn,1,1
Set ExcelApp =CreateObject("Excel.Application")
ExcelApp.Application.Visible = True
Set ExcelBook = ExcelApp.Workbooks.Add
ExcelBook.WorkSheets(1).cells(1,1).value ="用户表" 
ExcelBook.WorkSheets(1).cells(2,1).value = "用户编号"
ExcelBook.WorkSheets(1).cells(2,2).value = "登陆名"
ExcelBook.WorkSheets(1).cells(2,3).value = "真实姓名"
ExcelBook.WorkSheets(1).cells(2,4).value = "密码"
cnt =3
do while not rs.eof
ExcelBook.WorkSheets(1).cells(cnt,1).value = rs("provinceid")
ExcelBook.WorkSheets(1).cells(cnt,2).value = rs("province")
ExcelBook.WorkSheets (. 1) .Cells (CNT,. 3) .Value = RS ( "In Flag")
ExcelBook.WorkSheets (. 1) .Cells (CNT,. 4) .Value = RS ( "ID")
rs.MoveNext
CNT = CINT (CNT) +. 1
Loop
Excelbook.SaveAs "D: /yourfile.xls" 'this is the completion of an inventory after the data lead-in file into the D
ExcelApp.Application.Quit' derived after exit Excel
the Set ExcelApp = Nothing 'Excel object unregister
%>

 

<%
Set xlApplication = Server.CreateObject ( "Excel.Application") 'call excel objects
xlApplication.Visible = False' without opening excel
xlApplication.SheetsInNewWorkbook = 1 'to specify the number of tables in excel
xlApplication.Workbooks.Add' Add the Workbook
Set xlWorksheet = xlApplication.Worksheets (1) 'to generate a first sheet sub-object
xlWorksheet.name = "statistics"' designated sheet name
', and the width of the designated column alignment
xlApplication.ActiveSheet.Columns (1) .ColumnWidth = 5
xlApplication.ActiveSheet.Columns (. 1). 3 = .HorizontalAlignment
xlApplication.ActiveSheet.Columns (2) = 40 .ColumnWidth
xlApplication.ActiveSheet.Columns (2) =. 1 .HorizontalAlignment
xlApplication.ActiveSheet.Columns (. 3). 5 = .ColumnWidth
xlApplication. ActiveSheet.Columns (3) .HorizontalAlignment = 3
xlApplication.ActiveSheet.Columns (. 4) = 15 .ColumnWidth
xlApplication.ActiveSheet.Columns (. 4) =. 1 .HorizontalAlignment
xlApplication.ActiveSheet.Columns (. 5) = 12 is .ColumnWidth
xlApplication.ActiveSheet.Columns (. 5) =. 1 .HorizontalAlignment
xlApplication. ActiveSheet.Columns (. 6) = 12 is .ColumnWidth
xlApplication.ActiveSheet.Columns (. 6). 3 = .HorizontalAlignment
'xlApplication.ActiveSheet.Rows (I) = 30 .RowHeight' row height
"height specifies a particular column and row
xlWorksheet.Range (xlWorksheet.Cells (1,1), xlWorksheet.Cells ( 1,6)). MergeCells = True ' merger columns
xlWorksheet.Range ( "A1"). value = " 2005 statistics"
xlWorksheet.Range ( "A1") .font.Size = 14 'font size
xlWorksheet.Range ( "A1"). font.bold = true' bold
xlWorksheet.Range ( "A1").HorizontalAlignment = 3 'are aligned horizontally
xlWorksheet.Range("A1").VerticalAlignment=3'垂直对齐

xlWorksheet.Cells(2,1).Value = "序号"
xlWorksheet.Cells(2,2).Value = "标题"
xlWorksheet.Cells(2,3).Value = "图"
xlWorksheet.Cells(2,4).Value = "部门"
xlWorksheet.Cells(2,5).Value = "作者"
xlWorksheet.Cells(2,6).Value = "时间"

xlWorksheet.Range("A2:F2").Borders.LineStyle=1

'--------------------------------------------------自己可做循环i=i+1(数据库数据)
'xlWorksheet.Cells(2+i,1).Value = i
'xlWorksheet.Cells(2+i,2).Value = topic
'xlWorksheet.Cells(2+i,3).Value = img_str
'xlWorksheet.Cells(2+i,4).Value = nfrom
'xlWorksheet.Cells(2+i,5).Value = writer
'xlWorksheet.Cells(2+i,6).Value = ntime
'--------------------------------------------------
Set fs = CreateObject("Scripting.FileSystemObject")
tfile=Server.MapPath("test.xls")
if fs.FileExists(tfile) then
Set f = fs.GetFile(tfile)
f.delete true
Set f = nothing
end if
Set fs = nothing
xlWorksheet.SaveAs tfile '保存文件
xlApplication.Quit '释放对象
Set xlWorksheet = Nothing
Set xlApplication = Nothing
%>
<p align="center"><a href="downfile.asp?fileSpec=<%=tfile%>">下载</a></p>

downfile.asp
<%
Function downLoadFile(FileSpec)
on error resume next
Const ForReading=1
Const TristateTrue=-1
Const FILE_TRANSFER_SIZE=1024 '16384
Dim objFileSystem, objFile, objStream
Dim char
Dim sent
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
If objFileSystem.FileExists(fileSpec)=false Then
response.write("<Script>alert(""请求文件不存在!"");history.back();</script>")
Exit Function
End If
FileName = objFileSystem.GetFileName(FileSpec)
send=0
TransferFile = True
Set objFileSystem = Server.CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystem.GetFile(FileSpec)
Set objStream = objFile.OpenAsTextStream(ForReading, TristateTrue)
Response.AddHeader "content-type", "application/octet-stream"
Response.AddHeader "Content-Disposition","attachment;filename=" & filename

Response.AddHeader "content-length", objFile.Size
Do While Not objStream.AtEndOfStream
char = objStream.Read(1)
Response.BinaryWrite(char)
sent = sent + 1
If (sent MOD FILE_TRANSFER_SIZE) = 0 Then
Response.Flush
If Not Response.IsClientConnected Then
TransferFile = False
Exit Do
End If
End If
Loop
Response.Flush
If Not Response.IsClientConnected Then TransferFile = False
objStream.Close
Set objStream = Nothing
Set objFileSystem = Nothing
End Function
fileSpec =Lcase(Cstr(Trim(Request("fileSpec"))))
downLoadFile(fileSpec)
%>

Environment configuration
environment to configure the server from a reference point of view, Microsoft's series of configuration should do, namely:
1. PWS + Office + Win9x
2. Office Professional + PWS + Win2000
3. Win2000 Server + IIS + Office
is currently the author of a successful test environment is the latter two. Office versions are no special requirements, taking into account the uncertainty and lower client configuration compatibility features, we recommend that the server-side version of Office is not too high, in order to prevent the client download is not displayed correctly.
Server environment configuration there are two accidental discovery is:
1. Jinshan WPS2002 originally equipped with the author development machine, the result Excel object created problems always arise, after WPS2002 unloading, error disappears.
2. I like to use FrontPage to develop ASP code, and found that if FrontPage Open (server-side), object creation instability phenomenon, sometimes successful and sometimes unsuccessful. After extended study found that, if created Office series of software running on the server side, the Excel object is difficult to succeed.
The server must also be set that is operating authority COM components. At the command line, type "DCOMCNFG", then enter COM component configuration interface, select Microsoft Excel click the Properties button, the three options will always choose Custom, edit Everyone will add all permissions. Restart the server after saving is complete.
Environment configuration client did not find any place special attention, as long as Office and IE can be fitted, can seem generic version.

Two, ASP basic operation of Excel
1, establishing the Excel object
set objExcelApp = CreateObject ( "Excel.Application" )
objExcelApp.DisplayAlerts = false warnings are not displayed
objExcelApp.Application.Visible = false does not display interface
2, a new Excel file
objExcelApp.WorkBooks.add
SET objExcelBook = objExcelApp.ActiveWorkBook
SET objExcelSheets = objExcelBook.Worksheets
SET objExcelSheet objExcelBook.Sheets = (. 1)
. 3 read existing Excel file
strAddr = Server.MapPath ( ".")
objExcelApp.WorkBooks.Open (strAddr & "TempletTable.xls")
the SET objExcelBook = objExcelApp.ActiveWorkBook
the SET objExcelSheets = objExcelBook.Worksheets
the SET objExcelSheet = objExcelBook.Sheets ( 1)
4, save Excel files
objExcelBook.SaveAs strAddr & "TempTable.xls"
5, save Excel files
saved successfully objExcelBook.Save (when I test, an error page.)
6. quit Excel operations
objExcelApp.Quit exit must
set objExcelApp = Nothing

three, ASP operations generate data Excel table
1, inserted within a data range
objExcelSheet.Range ( "B3: k3") Value = Array ( "67", "87", ". 5 "," 9 "," 7 "," 45 "," 45 "," 54 "," 54 "," 10 ")
2, is inserted in a data cell
objExcelSheet.Cells (3,1) .Value = "the Internet Explorer"
. 3, to select a range of
4, the left cell Videos cells thick lines
5, thick lines drawn right cell
6, cell Videos upper thick line
7, the cell below the broad-brush painting
8, the cell background color setting
9 combined unit grid
10, is inserted into the line
11, is inserted into the column

four, ASP operations generate Excel Chart FIG.
1, FIG create Chart
objExcelApp.Charts.Add
2, FIG type setting Chart
objExcelApp.ActiveChart.ChartType = 97
Note: The two-dimensional line graph 4; two-dimensional pie, 5; D column chart 51
3 Chart FIG title set
objExcelApp.ActiveChart.HasTitle = True
= objExcelApp.ActiveChart.ChartTitle.Text "Test the Chart A"
. 4, by setting the graphics table data
objExcelApp.ActiveChart.SetSourceData objExcelSheet.Range ( "A1: K5"),. 1
. 5, the pattern data set directly (recommended)
objExcelApp. ActiveChart.SeriesCollection.NewSeries
objExcelApp.ActiveChart.SeriesCollection (. 1) .Name = "=" "333" ""
objExcelApp.ActiveChart.SeriesCollection (. 1) .Values = "= {1,4,5,6,2}"
. 6 binding chart Figure
objExcelApp.ActiveChart.Location 1
7, show data table
objExcelApp.ActiveChart.HasDataTable = True
8, show Legend
objExcelApp.ActiveChart.DataTable.ShowLegendKey = True

V. server-side Excel file browsing, download, delete programs
viewed many solutions, "Location.href =", "Navigate ", "Response.Redirect" can be achieved, the method proposed by the client, because the server more time to generate Excel files.
Download implementation will take some work. Use the Internet to download the server-side components off the shelf or custom-developed own components is a good program. Another method is the client operating on Excel, save operation by the client Excel file server to the client. This method requires the client to open operating authority unsafe ActiveX controls, taking into account the client will notify each server as a trusted site troublesome extent of the proposal is still using the first method is relatively easy.
Delete program consists of three parts:
A: Excel file generated by the same user with the same file name, the file name can be a user ID number or the like can be assured SessionID number strings will not be repeated. So that the new file is automatically covered when generating a file.
B: When setting Session_onEnd event fires in the Global.asa file, delete the temporary file that Excel users.
C: When setting Application_onStart event fires in the Global.asa file, delete all the files in the temporary directory.
Note: It is recommended directory structure Src code directory Templet template directory Temp temporary directory

VI Appendix
death process when an error occurs Excel emergence is a very difficult thing. Before each file with "On Error Resume Next" will help improve the situation, because no matter whether it will file an error to insist on the implementation of "Application.Quit", to ensure that each program to finish execution does not leave dead process

Published 16 original articles · won praise 1 · views 30000 +

Guess you like

Origin blog.csdn.net/wvtjplh/article/details/3851207