ASP.NET導出word實例


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();
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM