ASP.NET導出word實例
最近遇到一個題目就是如何在asp.net中將數據導出到word中,由于數據是動態的,所以需要在后臺拼出想要的的格式,翻遍了網頁找出了一個比較滿意的代碼,感謝那位高手。代碼如下:
public void Download(){Random rd = new Random();string fileName = DateTime.Now.ToString("yyyyMMddhhmm") + rd.Next() + ".doc";//存儲路徑string path = Server.MapPath(fileName);//創建字符輸出流StreamWriter sw = new StreamWriter(path, true, System.Text.UnicodeEncoding.UTF8);//需要導出的內容// string str = "<html><head><title>無標題文檔</title></head><body>這里放從數據庫導出的word文檔內容</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();}
?