C#開源組件DocX處理Word文檔基本操作(一)


C#中處理Word文檔,是大部分程序猿繞不過的一道門。小公司或一般人員會選擇使用開源組件。目前網絡上出現的帖子,大部分是NPOI與DocX,其它的也有。不啰嗦了,將要使用DocX的基本方法貼出來,供參考。

經過親測,DocX版本1.3.0.0比較穩定,基本功能使用正常(包括圖片,表格,正文及頁眉頁腳等),建議大家選擇該版本。目前為止(2020-01-23)官方最新版本為1.5.0.0,但其圖片功能有問題(最先測試,其它就沒深入了解了)。所以,若沒有特別說明,代碼中涉及的DocX版本為1.3.0.0。

DocX下載安裝,有兩種方式。一是開源官網下載,網址是:http://docx.codeplex.com/ ;二是在VS中使用NuGet,打開NuGet管理,查找DocX,即可看到可安裝版本。當然,為了使用DocX組件,你的系統需要安裝.NET框架4.0和Visual Studio 2010或更高版本。

DocX按版本不同,命名空間不一樣。在1.1.0.0之前,使用 using Novacode 方式;從1.1.0.0到1.3.0.0,使用 using Xceed.Words.NET 方式;從1.4.1.0起,有兩個:using Xceed.Words.NET 和 using Xceed.Document.NET。

文檔組成基本類似,也按段落、表格(行、列(段落))等方式,差別在使用時基本不考慮Run,要么是Append增加,要么是Insert插入,插入有文本插入與段落(表格)的之前、之后插入,如:InsertParagraphBeforeSelf 和 InsertTableAfterSelf 等方式。實際使用請自己理解體會,這不是太難的東西。

若DocX選擇版本1.3.0.0后,基本上按網上的代碼與使用貼,能夠處理大部分常用的Word文檔了。

再次強調,若無特別說明,DocX版本為:1.3.0.0,命名空間引用:using Xceed.Words.NET,DocX組件的文件名為:Xceed.Words.NET.Dll。

代碼示例如下:

private void DocX_DocMainBody()
        {
            string currPath = System.AppDomain.CurrentDomain.BaseDirectory;
            string docPath = Path.Combine(currPath, "DocxWord");
            if (!Directory.Exists(docPath))
                Directory.CreateDirectory(docPath);
            string outFile = Path.Combine(docPath, string.Format("{0}.Docx", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            string picFile = Path.Combine(currPath, "_Word.jpg");

            using (var document = File.Exists(outFile) ? DocX.Load(outFile) : DocX.Create(outFile))
            {
                Paragraph p1 = document.InsertParagraph();
                p1.InsertText("[1這是首頁 - 原始段落.]");        //當前插寫(或在指定位置寫入)
                p1.Append("[2增加表格]");
                Table tblAdd = p1.InsertTableAfterSelf(1, 4);   //插入段落后
                tblAdd.Design = TableDesign.TableGrid;
                tblAdd.Rows[0].Cells[0].Paragraphs.First().Append("3增加的表格").Alignment = Alignment.center;
                tblAdd.InsertParagraphAfterSelf("[4表格后增加段落]");

                p1.InsertParagraphBeforeSelf("[5原始段落前插入新段落]").Append("[6增加的新文本]").Bold().InsertText(0,"[7插入的新文本]");

                Table tbl = p1.InsertTableBeforeSelf(6, 3);     //插入段落前部
                tbl.Design = TableDesign.LightShading;
                tbl.Rows[0].Cells[0].Paragraphs.First().InsertText("[8增加表格]");
                tbl.Rows[0].Cells[1].Paragraphs.First().InsertText("[9共6行3列]");
                tbl.Rows[0].Cells[2].Paragraphs.First().InsertText("[10第3列]");
                tbl.Rows[1].Cells[0].Paragraphs.First().InsertText("[11Cell10]");
                tbl.Rows[1].Cells[1].Paragraphs.First().InsertText("[12Cell11]");
                tbl.Rows[1].Cells[2].Paragraphs.First().InsertText("[13Cell12]");

                Paragraph p1_1 = p1.InsertParagraphBeforeSelf("[14原始段落前插入的段落. 本段落后插入表格]");
                Table t_1 = p1_1.InsertTableAfterSelf(tblAdd);  //先插入段落再在插入的段落之前插入表格
                t_1.Rows[0].Cells[0].Paragraphs.First().InsertText("[15步驟14插入的表格]");
                t_1.InsertRow().Cells[1].Paragraphs.First().InsertText("[16增加一行]");
                t_1.InsertRow(0).Cells[0].Paragraphs.First().Append("[17在首行插入一行]");

                Paragraph p1_2 = p1.InsertParagraphAfterSelf("[18原始段落后插入的段落。本段落后插入3段空段落]");
                Paragraph p1_3 = p1_2.InsertParagraphAfterSelf("").InsertParagraphAfterSelf("").InsertParagraphAfterSelf("");

                p1_3.InsertPageBreakAfterSelf();  //該段落之后插入換頁符, 優先於同段落的表格插入

                Paragraph p2 = document.InsertParagraph();  //插入新段落
                p2 = p2.InsertParagraphAfterSelf("");
                p2 = p2.Append("[19這是第二頁.]");  //AppendLine: 會增加換行(先換行再寫入文本), Append: 不會換行
                p2 = p2.InsertParagraphAfterSelf("");
                Table t_2 = p2.InsertParagraphBeforeSelf("[20測試InsertParagraphAfterSelf(\"\")即增加空段落行,本段落是InsertParagraphBeforeSelf在InsertParagraphAfterSelf(\"\")的段落行之前插入,接着在本段落前插入2行3列的表格]").InsertTableBeforeSelf(2, 3);
                t_2.Design = TableDesign.TableGrid; //TableDesign.None;

                Paragraph pPic = document.InsertParagraph("[21以下插入圖片]", false);
                var image = document.AddImage(picFile);
                var picture = image.CreatePicture();
                //picture.Rotation = 10;  //旋轉
                picture.SetPictureShape(BasicShapes.cube);
                picture.Height = 48;
                picture.Width = 48;
                document.InsertParagraph().AppendPicture(picture);

                document.Save();  //document.SaveAs(outFile);
MessageBox.Show(Path.GetFileName(outFile) + " 完成!"); } }
View Code

 

代碼說明:以上代碼中字串的[##打頭的數字,是我測試處理時分析代碼作用效果用。在最后生成的Word文檔中,你從這些數字打頭的段落或位置上,可以直接看到代碼的作用,方便你初學時理解。

生成文檔效果:

基本的使用就是這些,希望能幫到你。

下一篇介紹用DocX來處理頁眉頁腳


免責聲明!

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



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