最近遇到一個題目就是如何在asp.net中將數(shù)據(jù)導出到word中,由于數(shù)據(jù)是動態(tài)的,所以需要在后臺拼出想要的的格式,翻遍了網(wǎng)頁找出了一個比較滿意的代碼,感謝那位高手。代碼如下:
public void Download() { Random rd = new Random(); string fileName = DateTime.Now.ToString("yyyyMMddhhmm") + rd.Next() + ".doc"; //存儲路徑 string path = Server.MapPath(fileName); //創(chuàng)建字符輸出流 StreamWriter sw = new StreamWriter(path, true, System.Text.UnicodeEncoding.UTF8); //需要導出的內(nèi)容 // string str = "<html><head><title>無標題文檔</title></head><body>這里放從數(shù)據(jù)庫導出的word文檔內(nèi)容</body></html>"; string str = ""; str += "<html><head><title>無標題文檔</title></head><body>"; str += "<div>閱讀報表</div>"; str += "<table border='1'><tr>"; str += "<td>20000</td>"; str += "<td>10000</td></tr><tr>"; str += "<td>30000</td>"; str += "<td>30000</td><tr>"; str += "</table></body></html>"; //寫入 sw.Write(str); sw.Close(); Response.Clear(); Response.Buffer = true; this.EnableViewState = false; Response.Charset = "utf-8"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.ContentType = "application/octet-stream"; Response.WriteFile(path); Response.Flush(); Response.Close(); Response.End(); }
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持VeVb武林網(wǎng)!
新聞熱點
疑難解答
圖片精選