C# WebForm 使用NPOI 2 產生簡單的word文檔(.docx)

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   使用   ar   for   

  使用NPOI可以方便的實現服務端對Word、Excel的讀寫。要實現對Word的讀寫操作,需要引用NPOI.OOXML.dll,應用命名空間XWPF。

  本文使用NPOI 2.0實現對Word的基本產生、下載操作。 NOPI 2.0 :http://npoi.codeplex.com/downloads/get/764162

雖然現在最新版本為NPOI 2.1.1 ,但筆者使用2.1.1的NPOI.OOXML.dll時,發現無法實現段落格式化功能,故推薦使用本文版本。

需要添加的命名空間:

1 using System.IO;2 using NPOI.XWPF.UserModel;

代碼:

 1         XWPFDocument doc = new XWPFDocument();      //建立新的word文檔 2          3         XWPFParagraph p1 = doc.CreateParagraph();   //向新文檔中添加段落 4         p1.SetAlignment(ParagraphAlignment.CENTER); //段落對其方式為置中 5  6         XWPFRun r1 = p1.CreateRun();                //向該段落中添加文字 7         r1.SetText("測試段落一"); 8  9         XWPFParagraph p2 = doc.CreateParagraph();10         p2.SetAlignment(ParagraphAlignment.LEFT);11 12         XWPFRun r2 = p2.CreateRun();13         r2.SetText("測試段落二");14 15 16         FileStream sw = File.Create("cutput.docx"); //...17         doc.Write(sw);                              //...18         sw.Close();                                 //在服務端組建檔案19 20         FileInfo file = new FileInfo("cutput.docx");//檔案儲存路徑及名稱  21                                                     //注意: 檔案儲存的父資料夾需添加Everyone使用者,並給予其完全控制許可權22         Response.Clear();23         Response.ClearHeaders();24         Response.Buffer = false;25         Response.ContentType = "application/octet-stream";26         Response.AppendHeader("Content-Disposition", "attachment;filename=" 27             + HttpUtility.UrlEncode("output.docx", System.Text.Encoding.UTF8));28         Response.AppendHeader("Content-Length", file.Length.ToString());29         Response.WriteFile(file.FullName);30         Response.Flush();                           //以上將產生的word檔案發送至使用者瀏覽器31 32         File.Delete("cutput.docx");                 //清除服務端產生的word檔案

頁面效果:

 

 

 

 

 

 

 

 

 

 

 

產生的word:

 

C# WebForm 使用NPOI 2 產生簡單的word文檔(.docx)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.