[.NET][C#]Office Word套版(Form) Open source

  • 15710
  • 0
  • .NET
  • 2016-02-10

因為程式在Server side產生Office套版文件出了一些小問題,case到微軟,依循微軟技術諮詢人員的建議,避免在Server端使用,雖然沒扣點數,但之後就一直找尋Microsoft.Office.Interop的替代方案:

  • 理所當然NPOI來取代Excel套版(Apache License 2.0)
  • 最近找了DocX來替代Word套版(Ms-PL)

 

 

一直以來都靠Microsoft.Office.Interop來產生Microsoft Office Word/Excel文件,但出現了一些小問題,可以參考這一篇KB255757:

裡面有一段文字寫到

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

 

OK! 改寫legacy code的好機會,今天筆記一下厲害的Word套版套件:DocX

Before: (template)

After:

超厲害的! 取代變數、表格及圖片都可以支援,而且套件的license type是Ms-PL!

 

1.服用方式: (Nuget套件安裝,搜尋DocX)

2.先建立一個Word Template範本,然後.NET 程式載入(輸入檔案位置):

WordDocument = DocX.Load(TemplateUrl);

3.取代變數

WordDocument.ReplaceText(範本上的變數, 值, false, System.Text.RegularExpressions.RegexOptions.None);

4.表格:

//找到範本中Table
Table t = WordDocument.Tables[0];
for (int row = 1; row < t.RowCount; row++)
{
    for (int cell = 0; cell < t.Rows[row].Cells.Count; cell++)
    {
        Paragraph cell_paragraph = t.Rows[row].Cells[cell].Paragraph;
        cell_paragraph.InsertText(dt.Rows[row - 1].ItemArray[cell].ToString(), false);
    }
}

是一個容易上手的word套表元件!

  • 目前沒有置換圖片的需求,以後再補筆記。
  • 套件支援Office2007、2010、2013

 

參考:

如何:使用 Visual C# 功能存取 Office Interop 物件 (C# 程式設計指南)

KB255757

Docx