asp教程.net匯入excel或word文檔代碼
//說明下 enableeventvalidation="false"的使用;
//在頁面上添加了輸入型伺服器控制項時(如 textbox),就需要設定為false了,否則會報錯;也就是關閉頁面驗證,預設是開啟的。
private void dbexport()
{
httpcontext.current.response.charset = "gb2312";
httpcontext.current.response.contentencoding = encoding.utf8;
//有部分文章裡使用的是utf7,是因為在特殊情況下中文會出現亂碼;這裡建議使用utf8,msdn中提到utf7沒有utf8安全性高;
//下面兩行可以保證其正確性,使用方法見代碼中
//response.write("<html><head><meta http-equiv=content-type content="text/html; charset=utf-8">");
//response.write("</body></html>");
//這裡對檔案名稱時行了編碼處理,以防止出現中文名稱亂碼的現象
httpcontext.current.response.appendheader("content-disposition", "attachment;filename=" + httputility.urlencode("檔案名稱.xls", encoding.utf8));
//匯出excel格式,因為格式不同,所以檔案名稱尾碼要根據實際情況進行調整(.xls)
httpcontext.current.response.contenttype = "vnd.ms-excel";
//匯出word格式,因為格式不同,所以檔案名稱尾碼要根據實際情況進行調整(.doc)
//httpcontext.current.response.contenttype = "vnd.ms-word";
//匯出html格式,因為格式不同,所以檔案名稱尾碼要根據實際情況進行調整(.html)
//httpcontext.current.response.contenttype = "text/html";
//還有兩種寫法好像是可以直接輸出映像,沒來得及加以考證,不過應該不是像上邊一樣改下格式就可以的,應該是先建立繪圖物件才可以設定response.contenttype才能輸出
//哪位有簡單的方式希望貼出來,學習下,謝謝
//httpcontext.current.response.contenttype = "image/gif";
//httpcontext.current.response.contenttype = "image/jpeg";
//說明下 divid 是什麼,這裡應該是你要轉出的控制項,可以是伺服器控制項也可以的html控制項(要加上 runat="server"否則這裡是找不到控制項的)
//我的頁面裡是一個 div id="divid" runat="server" 裡放了一個gridview用於顯示資料
divid.page.enableviewstate = false;
system.io.stringwriter tw = new system.io.stringwriter();
htmltextwriter hw = new htmltextwriter(tw);
divid.rendercontrol(hw);
//下邊的三行才是資料的輸出
response.write("<html><head><meta http-equiv=content-type content="text/html; charset=utf-8">");
httpcontext.current.response.write(tw.tostring());
response.write("</body></html>");
response.flush();
response.close();
}
//這個方法需要重寫,否則會報錯
public override void verifyrenderinginserverform(control control)
{
}