Web頁面數據導出方法概述之導出excel
2024-07-21 02:21:22
供稿:網友
前言:
隨著bs體系結構的廣泛使用,相對應的數據保存技術也要改進,對應web頁面,也就是我們通常認識到的html文件,由標示關鍵字與數據混合組成的文件。web頁面數據導出簡單地說,就是分離數據與格式,同時保存數據為另外一種格式。
正文:
分析http response等文件頭信息,對如何處理web頁面非常有用,下面簡單地介紹幾種常用的方法,算是在技術上學習,非理論上學習。
下面的代碼分析如何通過修改http頭文件,產生excel的文件供用戶下載,以達到數據導出的功能。這種非實際在服務器端生成文件的優點就是,對于并發請求該頁面的用戶來說不會發生服務器端文件同名覆蓋的問題!一般的解決方法有根據用戶名,ip,隨機數等。
dim resp as httpresponse
dim colcount as integer = mydatagrid.columns.count - 1
resp = page.response
resp.contentencoding = system.text.encoding.getencoding("gb2312") '解決中文亂碼之關鍵
'resp.charset = "utf-8"
'resp.addfiledependency(filename)
'resp.contenttype = "text/html"
''resp.appendheader("content-type", "text/html; charset=gb2312")
resp.contenttype = "text/csv" '通過修改文件類型可以讓用戶下載為csv類型的文件,修改text/**內容
resp.appendheader("content-disposition", "attachment;filename=" + filename + ".csv") '必要,做成下載文件
'實際從下載的保存文件類型來看,可以使txt,可以html,可以xls,用戶未必知道?且保存為xls的文件,數據包含在一列內
dim colheaders as string = ""
'imports system.text
dim stritems as stringbuilder = new stringbuilder
dim mycol as datagridcolumn
dim i as integer
for i = 0 to colcount
mycol = mydatagrid.columns(i)
if mycol.visible = true then
colheaders = colheaders & mycol.headertext.tostring & ","
end if
next
if colheaders.length > 0 then
colheaders = colheaders.substring(0, colheaders.lastindexof(","))
end if
colheaders = colheaders & chr(13) & chr(10)
resp.write(colheaders)
dim colrow as string
dim item as datagriditem
for each item in mydatagrid.items
resp.write(formatexportrow(colcount, item, mydatagrid))
‘將數據寫入對應的單元格
next item
resp.end()
也有描述如何將水晶報表導出為pdf文件保存的代碼,但是這種方式以及具體實現的過程,還在研究中。基本的想法是可以通過pdf然后利用插件打開,或者直接保存pdf