2012年4月30日 星期一

[C#] 將頁面上的table轉為word,excel格式

在網路上有很多教學,
看一看之後只知道,寫法大概就是這樣...
不過還是不大懂,為什麼要這樣宣告來著>"<
為什麼不能直接宣告一個變數就好這樣...

後來在一篇教學找到了解答!
http://www.dotnetperls.com/htmltextwriter

以下是該教學的 overview 說明:
Overview. The new StringWriter is required for the HtmlTextWriter to write to. It is a buffer and everything that is written is written to this. The using keyword ensures that the system will Dispose of the objects properly. It is not really required but may make for more efficient code.


針對 stringwriter 的詳細說明:
http://www.dotnetperls.com/stringwriter
StringWriter is used with HtmlTextWriter. A StringWriter instance is required in the constructor. In code that uses StringWriter, you can also use the internal StringBuilder: this allows you to convert method return values to string types.


看到這邊總算釐清了心中的疑惑來著,
HtmlTextWriter 和 StringWriter 根本是共生的嘛囧!
比起很多只是教"怎麼做"的文章,我個人還是喜歡從基礎的地方理解起~
比較能夠融會貫通的感覺吧!


MSDN 說明:
http://msdn.microsoft.com/zh-tw/library/system.web.ui.htmltextwriter(v=vs.80).aspx

以下正文~!

首先是宣告:

static System.IO.StringWriter strWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter word = new System.Web.UI.HtmlTextWriter(strWriter);

匯出的表格:

word.BeginRender();
word.RenderBeginTag("meta http-equiv=Content-Type content=\"text/html; charset=utf-8\"");
word.RenderBeginTag("body lang=ZH-TW style='tab-interval:24.0pt'");
MyTable.BorderColor = "#000000";        //將表格框線轉為黑色,否則預設灰色
MyTable.RenderControl(word);
word.RenderEndTag();
word.EndRender();

匯出方法:

Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AddHeader("Content-Disposition""attachment; filename=" + HttpUtility.UrlEncode(檔名".doc", System.Text.Encoding.UTF8));
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-word";
Response.Write(word);
Response.End();

參考:
http://codeasp.net/blogs/vivek_iit/microsoft-net/27/export-aspnet-page-to-word-excel-or-pdf
指定excel匯出格式
http://tw.myblog.yahoo.com/jw!xm1jOHyLGQfGU.bTjILU2g--/article?mid=1738
http://winnercow.pixnet.net/blog/post/23922362-%5Basp.net%5D-gridview-table%E6%BB%99%E5%87%BA-%E5%84%B2%E5%AD%98%E8%B3%87%E6%96%99%E8%87%B3excel,word,txt

http://social.msdn.microsoft.com/Forums/zh-HK/236/thread/9777139b-5624-4cfe-97f3-7432e94b8d0d

http://www.4ucode.com/Study/Topic/1513366

沒有留言:

張貼留言