使用開源word操作組件DocX的記錄


1.DocX簡介

1.1 簡介

  DocX是一個在不需要安裝word的情況下對word進行操作的開源輕量級.net組件,是由愛爾蘭的一個叫Cathal Coffey的博士生開發出來的。DocX使得操作word非常輕便,有利於減輕開發負擔,提升程序效率。DocX在Codeplex和Github上都有開源。

1.2 獲取與安裝

可以在http://docx.codeplex.com/releases下載獲取,也可以直接利用NuGet獲取。

Install-Package DocX

 

1.3 開發環境

用DocX需要.NET framework4.0和VS2010或更高版本。

2.DocX相關常用操作(持續更新中...)

2.1 創建word文檔

DocX document = DocX.Create(@"docs\HelloWorld.docx")

 

2.2 加載word文檔

DocX document = DocX.Load(@"docs\HelloWorld.docx")

 

2.3 書簽相關操作

2.3.1 插入書簽

var paragraph = document.InsertBookmark("firstBookmark");

2.3.2 根據書簽名獲取書簽

如果知道一個書簽的書簽名,可以直接得到。

var b = document.Bookmarks["書簽1"];

2.3.3 在書簽中插入文字

document.Bookmarks["書簽1"].SetText("Hello World!");

2.3.4 在書簽中插入圖片、表格

document.Bookmarks["書簽2"].Paragraph.InsertPicture(@"pic.jpg");
document.Bookmarks["書簽3"].Paragraph.InsertTableAfterSelf(t);//t是Table類型

 

2.4 分節符和分頁符

2.4.1 分節符

document.InsertSectionPageBreak();//分節符

2.4.2 分頁符

  Paragraph p = document.InsertParagraph();
  p.InsertPageBreakAfterSelf();//分頁符

 

2.5 添加目錄

 1  static void AddToc()
 2         {
 3             Console.WriteLine("\tAddToc()");
 4 
 5             using (var document = DocX.Create(@"docs\Toc.docx"))
 6             {
 7                 document.InsertTableOfContents("目錄", TableOfContentsSwitches.O | TableOfContentsSwitches.U | TableOfContentsSwitches.Z | TableOfContentsSwitches.H, "Heading2");
 8                 var h1 = document.InsertParagraph("Heading 1");
 9                 h1.StyleName = "Heading1";
10                 document.InsertParagraph("Some very interesting content here");
11                 var h2 = document.InsertParagraph("Heading 2");
12                 document.InsertSectionPageBreak();
13                 h2.StyleName = "Heading1";
14                 document.InsertParagraph("Some very interesting content here as well");
15                 var h3 = document.InsertParagraph("Heading 2.1");
16                 h3.StyleName = "Heading2";
17                 document.InsertParagraph("Not so very interesting....");
18 
19                 document.Save();
20             }
21         }

 2.6 插入圖片

Image img = document.AddImage(@"pic.jpg");
Picture pic = img.CreatePicture();
Paragraph p1 = document.InsertParagraph();
p1.InsertPicture(pic);

 

2.7 操作表格

2.7.1 創建和插入表格

Table t = document.AddTable(3, 4);//三行四列

 

2.7.2 單元格合並

Table t = document.AddTable(3,4);
t.MergeCellsInColumn(0, 0, 1);//public void MergeCellsInColumn(int columnIndex, int startRow, int endRow);豎向合並
t.Rows[0].MergeCells(1, 2);//public void MergeCells(int startIndex, int endIndex);橫向合並

注:合並單元格的時候注意,最好先豎向合並,再橫向合並,以免報錯,因為橫向合並會改變列數。

3. 資源

開源網址:http://docx.codeplex.com/ (里面的示例代碼很適合初學者學習)

高質量博客推薦:http://www.cnblogs.com/asxinyu/archive/2013/02/22/2921861.html#_label3

利用DocX操作word的開源小項目:https://github.com/hahahuahai/create-word-by-DocX

 


免責聲明!

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



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