iT邦幫忙

1

asp 查詢結果 匯出EXCEL

asp
Pyan 2019-08-27 11:26:306185 瀏覽
  • 分享至 

  • twitterImage

.html
https://ithelp.ithome.com.tw/upload/images/20190827/201198458D7vtZgVQZ.png
.asp
https://ithelp.ithome.com.tw/upload/images/20190827/20119845uMVC1YRLLS.png

<% 
Response.AddHeader "Content-Disposition","attachment;filename=test.xls"
Response.ContentType = "application/vnd.ms-excel"
%>

我試了這個方法但是 按下送出後會直接下載一個.xls(資料是對的)
但希望是可以在第二張圖 放一個按鍵 可以先看到查詢結果 再按匯出成.xls檔

<html>
<head>
</head>
<body>

<%
id = request("Id")
num = request.form("num")
cls = request.form("class")

if len(id) <> 0 then
x= "and ID= '" &id& "'"
End if

if len(num) <> 0 then
y= "and number='" &num&"'"
End if

if len(cls) <> 0 then
z= "and class=" &cls
End if

%>

<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.open"PROVIDER=SQLOLEDB;DATA SOURCE=N00WIN10-00;UID=sa;PWD=000000;DATABASE=CH03" 

sql = "select * from list where name like '%" & request.form("name")&"%'"  + x + y + z 

set rs = Server.CreateObject("ADODB.recordset")
rs.Open sql , conn
%>

<table border="1"   width="40%">

<tr> 
   <%for each y in rs.Fields
    response.write("<th>" & y.name & "</th>")
next%>
</tr>

<%do until rs.EOF%>
<tr>
  <%for each x in rs.Fields%>
    <% Response.Write("<td>"& x.value & "</td>")%> 
  <%next 
  rs.MoveNext
  %>
</tr> 
<%
loop
rs.close
conn.close
%>
</table>

</body>
</html>
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

4
ccutmis
iT邦高手 2 級 ‧ 2019-08-27 17:08:22
最佳解答
<% If Request("downloadXLS") <> "" Then %>
<%
Response.AddHeader "Content-Disposition","attachment;filename=test.xls"
Response.ContentType = "application/vnd.ms-excel"
%>
<%
'這裡輸出EXCEL內容(請依實際需要修改)
%>
<% ELSE %>
<!doctype html><html><head>..略...</head><body>
<%
'這裡輸出網頁表格內容(請依實際需要修改)
%>
<form action="" method="POST">
<input type="hidden" name="downloadXLS" value="1" />
<input type="submit" name="submit" value="下載XLS"/>
</form>
</body></html>
<% END If %>

說明 :
上面的範例是單頁asp,用表單變數判斷是要顯示html內容或是下載XLS,
這是邏輯而已沒有經過實測(我手邊也沒有IIS4可以安裝)
若覺得上面範例不好也可以試另一種笨方法,
就是查詢表單一頁(a.asp),網頁表單一頁(b.asp),下載XLS一頁(c.asp)
執行流程就是a.asp → b.asp
然後在 b.asp裡面放 c.asp的超連結(或參考上面的form處理傳參數給c.asp)
這樣是很笨但能運作的另一種方法。

asp是古董級網頁伺服器語言(IIS4),
建議如果是初學者學習的話,直接改學別套會比較好(例如PHP7或ASP.NET MVC等等)。

我要發表回答

立即登入回答