Word Document 代码操作 对象模型

如果我们需要对文档进行操作,那就一定要使用Document这个类了。这个类存在于aspose.word命名空间下,使用之前需要using这个命名空间。

 

内容列表:

1、创建和打开文档

2、文档合并

3、接受修订与页眉页脚替换
4、向文档内写入文字,图片及表格

5、插入页眉页脚

 

1、打开文件方法:Document有四个构造函数可以用来打开已经存在的Word文档,或者创建一个空白的文档它们分别如下:

a、创建一个空白的文档

public Document();示例如下:

/// <summary>
        /// 打开一个空白文件
        /// </summary>
        private void OpenBlankDoc()
        {
            //创建一个空白文档,并且默认包含一个空的段落
            Document doc = new Document();
            // 创建一个新的文字文本
            Run run = new Run(doc, "Hello");
            // 为文本指定格式
            Aspose.Words.Font f = run.Font;
            f.Name = "Courier New";
            f.Size = 36;
            // 增加文本到当前文档第一个段落的结尾
            doc.FirstSection.Body.Paragraphs[0].AppendChild(run);
        }

 

b、从流中打开一个文档,并自动发现内容的格式

public Document(Stream);示例代码如下

/// <summary>
        /// 从流中打开一个文档,并自动发现内容的格式
        /// </summary>
        private void OpenDocFromSteam()
        {
            // 打开一个字节流动.以只读的方式访问指定文档的内容.
            Stream stream = File.OpenRead("c:\\Document.doc");
            // 加载全部数据到内容中.
            Document doc = new Document(stream);
            // 因为文档的内容已经加载到内存中,所以,此处可以关闭字段流了。
            stream.Close();
            // ... 对内存中的文档做其它操作
        }

 

 

/// <summary>
        /// 打开网络地址上的文档
        /// </summary>
        private void OpenDocFromNet()
        {
            // URL地址指定从何处打开文档
            string url = "http://www.aspose.com/demos/.net-components/aspose.words/csharp/general/Common/Documents/DinnerInvitationDemo.doc";
            // 通过使用System.Net.WebClient 类,创建他的一个实例,并传递一个URL参数,以从指定的URL地址下载文档数据
            WebClient webClient = new WebClient();
            // 从URL地址下载文档数据.
            byte[] dataBytes = webClient.DownloadData(url);
            // 打包字字数据并保存到内存对像中
            MemoryStream byteStream = new MemoryStream(dataBytes);
            // 加载内存中的数据到一个新的Aspose.Word文档中,文件格式根据内容来自动推断,你可以用此方法来加载任何被Aspose.Words 支持的文档
            Document doc = new Document(byteStream);
            //通过另存为的方法,转换为任意Aspose.Words 支持的对象.
            doc.Save("c:\\Document.OpenFromWeb\\Out.doc");
        }

 

 

C、从字符流中打开文档,并可以指定额外的属性,如.加密密码等:

public Document(Stream,LoadOptions);示例代码如下:(由于此项只对6.5版本以上有效,此处不做代码演示,感兴趣的可以到http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/aspose.words.documentconstructor.html查看

 

 

通过路径打开一个存在的文档,用的最多的方法

public Document(string);示例代码如下:

 

Document doc = new Document(MyDir + "Document.doc");

 

 

d、打开一个已经存在的文档,并可以增加额外的属性.

public Document(string,LoadOptions);示例代码如下:(由于此项只对6.5版本以上有效,此处不做代码演示,感兴趣的可以到http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/aspose.words.documentconstructor.html查看

 

 

2、知道了如何打开文档,那接到就是如何对文档进入操作了,下面我只介绍一些需要在NPDS项目中使用到的方法。

 

a.合并两个或多个文件AppendDocument()方法,第二个参数为合并的格式,可以选择保留原有格式还是匹配目标格式。

 

示例代码一如下:

 Document DOC = new Document(HttpContext.Current.Server.MapPath("~/DOC/2011年软件水平考试软件设计师辅导资料.doc"));
            Document doc2 = new Document(HttpContext.Current.Server.MapPath("~/DOC/工作周报样例.docx"));
          //  Document doc3 = new Document(HttpContext.Current.Server.MapPath("~/DOC/TW文件清单.xlsx"));
            doc2.AppendDocument(DOC, ImportFormatMode.KeepSourceFormatting);

 

示例代码二如下:

// 定义文档模板的路径.
string folderPath = MyDir + "Templates";
//以下示例将展示如何把一个目录下的所有文档合并到一个文档中

Document baseDoc = new Document();


// 为模板增加一些内容.
DocumentBuilder builder = new DocumentBuilder(baseDoc);
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("Template Document");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal;
builder.Writeln("Some content here");


// 如果路径不存在则什么都不做

if (!Directory.Exists(folderPath))
    return;


// 查找当前目录下所有的doc为扩展名的文档

ArrayList files = new ArrayList(Directory.GetFiles(folderPath, "*.doc"));
// 为文件列表排序,以按照字母的先后顺序把文档合并到一起.
files.Sort();


// 检查路径是否存在
if (Directory.Exists(folderPath))
{
    //通过循环每一个文件,将内容增加到模板中.
    foreach (string file in files)
    {
        Document subDoc = new Document(file);
        baseDoc.AppendDocument(subDoc, ImportFormatMode.UseDestinationStyles);
    }
}


// 保存文档到硬盘上.
baseDoc.Save(MyDir + "Document.AppendDocumentsFromFolder Out.doc");

 

3、接受修订AcceptAllRevisions()与页眉页脚替换footer.Range.Replace()示例代码如下:

 Document DOC = new Document(HttpContext.Current.Server.MapPath("~/DOC/2011年软件水平考试软件设计师辅导资料.doc"));
            HeaderFooterCollection headersFooters = DOC.FirstSection.HeadersFooters;
            Aspose.Words.HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];
            //不能替换为空
            footer.Range.Replace("上学吧", "thid is footer", false, false);
              DOC.AcceptAllRevisions();//接受所有修订
            DOC.Save("xxx.doc", SaveFormat.Docx, SaveType.OpenInWord, HttpContext.Current.Response);

 

 

4、此方法需要使用到DocumentBuilder类。代码如下:

private void insertImage()
        {
            Document doc = new Document();
            // Create a document builder to insert content with into document.
            DocumentBuilder builder = new DocumentBuilder(doc);

 

#region 插入图片
builder.InsertImage(HttpContext.Current.Server.MapPath("~/DOC/jquery.png"), 100, 100);//指定要插入的图片路径,以及长度和宽度就可以了。还有其它一些重载的方法,大家可以参考(http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/aspose.words.documentbuilder.insertimage_overloads.html);
           

            #endregion ---------------------------------------------
            #region 插入文字
            builder.Writeln("你好,欢迎光临");//l输出一行文本
            builder.Writeln("谢谢");
            builder.Write(",不客气");//在当前行输出文本
            builder.Write(",不客气和我在同一行哟");
            #endregion-----------------------------------------------
            #region 插入表格
            builder.StartTable();//开始插入表格
            // I插入一个列
            builder.InsertCell();
            builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//设置对其方式
            builder.Write("This is row 1 cell 1");
            //  I插入一个列
            builder.InsertCell();
            builder.Write("This is row 1 cell 2");
            builder.EndRow();//每行完了以后调用此方法,转到下一行
            // 为新行使用新格式
            builder.RowFormat.Height = 100;
            builder.RowFormat.HeightRule = HeightRule.Exactly;
            // 插入一个列
            builder.InsertCell();
            builder.CellFormat.Orientation = TextOrientation.Upward;
            builder.Writeln("This is row 2 cell 1");
            // 插入一个列
            builder.InsertCell();
            builder.CellFormat.Orientation = TextOrientation.Downward;
            builder.Writeln("This is row 2 cell 2");
            builder.EndRow();//行结束
            builder.EndTable();//列结束
            #endregion
            builder.Document.Save("xxx.docx", SaveFormat.Docx, SaveType.OpenInWord, HttpContext.Current.Response);

        }

 

 

5、插入页眉页脚示例代码如下:

 

 private void MoveToMethod()
        {
            //创建一个空白文档
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            // 进行页面设置,指定节之间使用不同的页眉和页脚
            builder.PageSetup.DifferentFirstPageHeaderFooter = true;
            builder.PageSetup.OddAndEvenPagesHeaderFooter = true;
            // 创建页眉
            builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);//首页
            builder.Write("Header First");
            builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);//偶数页
            builder.Write("Header Even");
            builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);//奇数页
            builder.Write("Header Odd");
            //创建页脚
            builder.MoveToHeaderFooter(HeaderFooterType.FooterFirst);//首页
            builder.Write("Footer First");
            builder.MoveToHeaderFooter(HeaderFooterType.FooterEven);//偶数页
            builder.Write("Footer Even");
            builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);//奇数页
            builder.Write("Footer Odd");
            //创建三个新的页面每个页面代表一个章节
            builder.MoveToSection(0);//移动到第一个章节
            builder.Writeln("Page1");
            builder.InsertBreak(BreakType.PageBreak);//插入新的章节
            builder.Writeln("Page2");
            builder.InsertBreak(BreakType.PageBreak);//插入新的章节
            builder.Writeln("Page3");
            builder.InsertBreak(BreakType.PageBreak);//插入新的章节
            builder.Writeln("Page4");
            builder.InsertBreak(BreakType.PageBreak);//插入新的章节
            builder.Writeln("Page5");
            builder.Document.Save("xxx.docx", SaveFormat.Docx, SaveType.OpenInWord, HttpContext.Current.Response);
        }

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aspose.Words;
using Aspose.Words.Properties;
using log4net;
using System.IO;
using System.Diagnostics;
using Aspose.Words.Tables;
using Aspose.Words.Drawing;
using Aspose.Words.Lists;
using Aspose.Words.Fields;

namespace Test
{
    public partial class Form1 : Form
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Form1).Name);

        private String tbmessage = "";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Aspose.Words.License license = new Aspose.Words.License();
            license.SetLicense("License.lic");


        }

        /**
         * 这是生成文档的试验代码
         * @parameter sender
         * @parameter e
         */
        private void button1_Click(object sender, EventArgs e)
        {
            tbStatus.Text = "正在创建。。。。。。";
            Document doc = new Document("c://4add.doc");
            DocumentBuilder builder = new DocumentBuilder(doc);
            try
            {
                //写入字符串
                builder.Writeln("Hello World");
                builder.Writeln("{FOR REPLACE}");

                //Form Field
                string[] items = { "One", "Two", "Three" };

                builder.InsertComboBox("DropDown", items, 0);

                //在插入文本前定制文件属性.

                Aspose.Words.Font font = builder.Font;

                font.Size = 24;

                font.Bold = true;

                font.Color = Color.Blue;

                font.Name = "Arial";

                font.Underline = Underline.Dash;

                builder.Write("Sample text.");


                /**
                 * Set paragraph formatting properties
                 * */
                ParagraphFormat paragraphFormat = builder.ParagraphFormat;
                //paragraphFormat.Alignment = ParagraphAlignment.Center;
                //paragraphFormat.LeftIndent = 0;
                //paragraphFormat.RightIndent = 50;
                //paragraphFormat.SpaceAfter = 25;

                // Output text
                builder.Writeln("I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping.");
                builder.Writeln("I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like.");


                
                //读出属性值
                Console.WriteLine("1. Document name: {0}", "output.doc");

                Console.WriteLine("2. Built-in Properties");
                foreach (DocumentProperty prop in doc.BuiltInDocumentProperties)

                    Console.WriteLine("{0} : {1}", prop.Name, prop.Value);

                Console.WriteLine("3. Custom Properties");

                foreach (DocumentProperty prop in doc.CustomDocumentProperties)

                  Console.WriteLine("{0} : {1}", prop.Name, prop.Value);

                //输出Doc的Style
                StyleCollection styles = doc.Styles;
                foreach (Style style in styles)
                   Console.WriteLine("style name:"+style.Name);

                //增加一个Section
                Section sectionToAdd = new Section(doc);
                doc.Sections.Add(sectionToAdd);

                SectionCollection sections = doc.Sections;
                Console.WriteLine("doc.sections.length=" + sections.Count);

                
                /**
                 * Moving Cursor
                 **/
                //移动到文件头和文件尾
                builder.MoveToDocumentEnd();
                builder.Writeln("This is the end of the document.");

                builder.MoveToDocumentStart();
                builder.Writeln("This is the beginning of the document.");

                //移动到文件的任意节点
                builder.MoveTo(doc.FirstSection.Body.LastParagraph);
                builder.MoveToDocumentEnd();

 

                //移动到Section
                builder.MoveToSection(1);
                builder.Writeln("This is the 3rd section.");

                //移动到Section中的Paragraph
                // Parameters are 0-index. Moves to third paragraph.
                builder.MoveToParagraph(1, 0);
                builder.Writeln("This is the 2rd paragraph.");

 

 

                //移动到页眉和页脚 
                // Specify that we want headers and footers different for first, even and odd pages.
                builder.PageSetup.DifferentFirstPageHeaderFooter = true;
                builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

                // Create three pages in the document.
                builder.MoveToSection(0);
                builder.Writeln("Page1");
                builder.InsertBreak(BreakType.PageBreak);
                builder.Writeln("Page2");
                builder.InsertBreak(BreakType.PageBreak);
                builder.Writeln("Page3");

                // Create the headers.
                builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
                builder.Write("Header First");
                builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
                builder.Write("Header Even");
                builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
                builder.Write("Header Odd");

                //Move to a table cell.
                // All parameters are 0-index. Moves to the 2nd table, 3rd row, 5th cell.
                //builder.MoveToCell(1, 2, 4, 0);
                //builder.Writeln("Hello World!");

 

                //得到当前的Node和Paragraph
                Node curNode = builder.CurrentNode;
                Paragraph curParagraph = builder.CurrentParagraph;

 

                /**
                 * 替换**/

                doc.Range.Replace("{FOR REPLACE}", "IS_PLACED", false, false);

                /** Range**/
                string text = doc.Range.Text;
                string text2 = doc.Sections[0].Range.Text;

                /**
                 * 插入一个文档
                 * */
                //先退到文档开头,插入模板
                builder.MoveToSection(0);
                builder.MoveToDocumentStart();
                //curNode = builder.CurrentNode;
                //curParagraph = builder.CurrentParagraph;
                //插入的一种方式
                Document doctemp = new Document("c://testtemplate.doc");
                //InsertDocument(curParagraph, doctemp);

                //插入的第二种方式 
                doc.AppendDocument(doctemp,ImportFormatMode.KeepSourceFormatting);


                //插入一个PAGE 域
                builder.Writeln("Page Number: ");
               //FieldStart pageField = builder.InsertField("PAGE","");
                builder.InsertField("PAGE", "");

             
                doc.UpdatePageLayout();
                doc.UpdateFields();

                //保存成PDF
                //保存成Doc
                builder.Document.Save("c://" + "output.doc");
                tbStatus.Text = "创建成功";


                //计算页码
                builder.MoveToDocumentEnd();
                int secCount = doc.Sections.Count;
                builder.MoveToSection(secCount - 1);


                int pages = doc.PageCount;
                int curPage = doc.BuiltInDocumentProperties.Pages;

                tbMessage.Text = "文件的当前页码数是:" + curPage+"/r/n";
                tbMessage.Text += "文件所有页码数(含封面和目录页)是:"+pages +"/r/n";


              

            }
            catch (Exception ex) {
                tbMessage.Text = "创建失败:" + ex.Message;
            }

 

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            tbStatus.Text = "打开Word文档";
            try
            {
                Process p = Process.Start("c://output.doc");               
            }
            catch (Exception ex)
            {
                tbMessage.Text = "打开Word文档失败(c://output.doc)!!具体原因是:" + ex.Message;
            }
        }


        /**
         * 
         * 创建一个页眉页脚中有表格的应用
         * 
         * **/

        private void btnGernerateDoc2_Click(object sender, EventArgs e)
        {
            tbStatus.Text = "正在创建。。。。。。";
            Document doc = new Document();

            DocumentBuilder builder = new DocumentBuilder(doc);


            try
            {


                Section currentSection = builder.CurrentSection;

                PageSetup pageSetup = currentSection.PageSetup;

 

                // Specify if we want headers/footers of the first page to be different from other pages.

                // You can also use PageSetup.OddAndEvenPagesHeaderFooter property to specify

                // different headers/footers for odd and even pages.

                pageSetup.DifferentFirstPageHeaderFooter = true;

 

                // --- Create header for the first page. ---

                pageSetup.HeaderDistance = 20;

                builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);

                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

 

                // Set font properties for header text.

                builder.Font.Name = "Arial";

                builder.Font.Bold = true;

                builder.Font.Size = 14;

                // Specify header title for the first page.

                builder.Write("Aspose.Words Header/Footer Creation Primer - Title Page.");

 

                // --- Create header for pages other than first. ---

                pageSetup.HeaderDistance = 20;

                builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

 

                // Insert absolutely positioned image into the top/left corner of the header.

                // Distance from the top/left edges of the page is set to 10 points.

                string imageFileName = "c://test.png";

                builder.InsertImage(imageFileName, RelativeHorizontalPosition.Page, 10, RelativeVerticalPosition.Page, 10, 50, 50, WrapType.Through);

 

                builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;

                // Specify another header title for other pages.

                builder.Write("Aspose.Words Header/Footer Creation Primer.");

 

                // --- Create footer for pages other than first. ---

                builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);

 

                // We use table with two cells to make one part of the text on the line (with page numbering)

                // to be aligned left, and the other part of the text (with copyright) to be aligned right.

                builder.StartTable();

 

                // Calculate table width as total page width with left and right marins subtracted.

                double tableWidth = pageSetup.PageWidth - pageSetup.LeftMargin - pageSetup.RightMargin;

 

                builder.InsertCell();

                // Set first cell to 1/3 of the page width.

                builder.CellFormat.Width = tableWidth / 3;

 

                // Insert page numbering text here.

                // It uses PAGE and NUMPAGES fields to autocalculate current page number and total number of pages.

                builder.Write("Page ");

                builder.InsertField("PAGE", "");

                builder.Write(" of ");

                builder.InsertField("NUMPAGES", "");

 

                // Align this text to the left.

                builder.CurrentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Left;

 

                builder.InsertCell();

                // Set the second cell to 2/3 of the page width.

                builder.CellFormat.Width = tableWidth * 2 / 3;

 

                builder.Write("(C) 2006 Aspose Pty Ltd. All rights reserved.");

 

                // Align this text to the right.

                builder.CurrentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Right;

 

                builder.EndRow();

                builder.EndTable();

 

                builder.MoveToDocumentEnd();

                // Make page break to create a second page on which the primary headers/footers will be seen.

                builder.InsertBreak(BreakType.PageBreak);

 

                // Make section break to create a third page with different page orientation.

                builder.InsertBreak(BreakType.SectionBreakNewPage);

 

                // Get the new section and its page setup.

                currentSection = builder.CurrentSection;

                pageSetup = currentSection.PageSetup;

 

                // Set page orientation of the new section to landscape.

                pageSetup.Orientation = Aspose.Words.Orientation.Landscape;

 

                // This section does not need different first page header/footer.

                // We need only one title page in the document and the header/footer for this page

                // has already been defined in the previous section

                pageSetup.DifferentFirstPageHeaderFooter = false;

 

                // This section displays headers/footers from the previous section by default.

                // Call currentSection.HeadersFooters.LinkToPrevious(false) to cancel this.

                // Page width is different for the new section and therefore we need to set

                // a different cell widths for a footer table.

                currentSection.HeadersFooters.LinkToPrevious(false);

 

                // If we want to use the already existing header/footer set for this section

                // but with some minor modifications then it may be expedient to copy heders/footers

                // from the previous section and apply the necessary modifications where we want them.

                CopyHeadersFootersFromPreviousSection(currentSection);

 

                // Find the footer that we want to change.

                HeaderFooter primaryFooter = currentSection.HeadersFooters[HeaderFooterType.FooterPrimary];

 

                // Calculate the table width to fit the current page width.

                tableWidth = pageSetup.PageWidth - pageSetup.LeftMargin - pageSetup.RightMargin;

 

                Row row = primaryFooter.Tables[0].FirstRow;

                row.FirstCell.CellFormat.Width = tableWidth / 3;

                row.LastCell.CellFormat.Width = tableWidth * 2 / 3;

 


                //插入一个PAGE 域
                builder.Writeln("Page Number: ");
                builder.InsertField("PAGE", "");


                doc.UpdatePageLayout();
                doc.UpdateFields();


                // Save the resulting document.

                doc.Save("c://output.doc");
                tbStatus.Text = "创建成功";

            }
            catch (Exception ex)
            {
                tbMessage.Text = "创建失败:" + ex.Message;
            }

           


        }

        /// <summary>

        /// Clones and copies headers/footers form the previous section to the specified section.

        /// </summary>

        private static void CopyHeadersFootersFromPreviousSection(Section section)
        {

            Section previousSection = (Section)section.PreviousSibling;

 

            if (previousSection == null)

                return;

 

            section.HeadersFooters.Clear();

 

            foreach (HeaderFooter headerFooter in previousSection.HeadersFooters)

                section.HeadersFooters.Add(headerFooter.Clone(true));

        }


        /// <summary>

        /// 插入一个文档到另外一个文档 
        /// Inserts content of the external document after the specified node.

        /// Section breaks and section formatting of the inserted document are ignored.

        /// </summary>

        /// <param name="insertAfterNode">Node in the destination document after which the content

        /// should be inserted. This node should be a block level node (paragraph or table).</param>

        /// <param name="srcDoc">The document to insert.</param>

        public static void InsertDocument(Node insertAfterNode, Document srcDoc)
        {

            // Make sure that the node is either a pargraph or table.

            if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &

              (!insertAfterNode.NodeType.Equals(NodeType.Table)))

                throw new ArgumentException("The destination node should be either a paragraph or table.");

 

            // We will be inserting into the parent of the destination paragraph.

            CompositeNode dstStory = insertAfterNode.ParentNode;

 

            // This object will be translating styles and lists during the import.

            NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

 

            // Loop through all sections in the source document.

            foreach (Section srcSection in srcDoc.Sections)
            {

                // Loop through all block level nodes (paragraphs and tables) in the body of the section.

                foreach (Node srcNode in srcSection.Body)
                {

                    // Let's skip the node if it is a last empty paragarph in a section.

                    if (srcNode.NodeType.Equals(NodeType.Paragraph))
                    {

                        Paragraph para = (Paragraph)srcNode;

                        if (para.IsEndOfSection && !para.HasChildNodes)

                            continue;

                    }

 

                    // This creates a clone of the node, suitable for insertion into the destination document.

                    Node newNode = importer.ImportNode(srcNode, true);

 

                    // Insert new node after the reference node.

                    dstStory.InsertAfter(newNode, insertAfterNode);

                    insertAfterNode = newNode;

                }

            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }


        /// <summary>
        /// 生成表格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_2(object sender, EventArgs e)
        {
            tbStatus.Text = "正在创建。。。。。。";
            
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            try
            {

 


                for (int i = 0; i < 10; i++)
                {
                    //新建一个标题 
                    //builder.ListFormat.ListLevelNumber = 3;
                    //Style listStyle = doc.Styles["sfi"];
                    //List list1 = listStyle.List;
                    //ListLevel level = list1.ListLevels[i];
                    //builder.ParagraphFormat.Style = doc.Styles["Normal"];
                   // builder.ParagraphFormat.Style = doc.Styles["Heading1"];
                    //builder.ListFormat.List = list1;

                    builder.Writeln("这是第" + i + "个表格");
                    //增加一行
                    builder.InsertParagraph();
                    //清空Style
                    
                    builder.ListFormat.List = null;
                   


                    //开始一个表格
                    builder.StartTable();
                    //插入Cell
                    builder.InsertCell();
                    builder.InsertCell();
                    builder.InsertCell();
                    double xx = builder.CellFormat.Width;

                    tbMessage.Text = "表格单元原始长度为:" + xx;
                    //调整长度
                    builder.CellFormat.Width = 300;

                    builder.EndRow();
                    //恢复长度
                    builder.CellFormat.Width = xx;
                    //插入Cell
                    builder.InsertCell();
                    builder.InsertCell();
                    builder.InsertCell();

                    tbMessage.Text = "表格单元原始长度为:" + xx;
                    //调整长度
                    builder.CellFormat.Width = 300;
                    builder.EndRow();
                    //恢复长度
                    builder.CellFormat.Width = xx;


                    //插入Cell
                    builder.InsertCell();
                    builder.InsertCell();
                    builder.InsertCell();

                    tbMessage.Text = "表格单元原始长度为:" + xx;
                    //调整长度
                    builder.CellFormat.Width = 300;
                    builder.EndRow();
                    //恢复长度
                    builder.CellFormat.Width = xx;
          

                    builder.EndTable();
                    //增加一行
                    builder.InsertParagraph();

                }

                String[] aaaa = { "编号","姓名","家庭住址"};
                String[] bbbb = { "张三","朝阳区芍药居","李四","海淀区远大路蓝靛厂东路2号金源时代商务中心写字楼B座11D室"};
               
                /**
                 * 往表里写内容**/

                //表-10个
                for (int t = 0; t < 10; t++ )
                {
                    for(int m=0;m<bbbb.Length;)
                    {
                        m = 0;

                        //
                        for (int i = 0; i < 3; i++)
                        {
                            
                            //
                            for (int j = 0; j < 3; j++)
                            {
                                builder.MoveToCell(t, i, j, 0);
                                //第一行表头
                                if (i == 0)
                                {
                                    builder.Font.Bold = true;
                                    builder.Write(aaaa[j]);
                                    builder.Font.Bold = false;
                                }
                                //序号
                                else if (j == 0)
                                {
                                    builder.Write(""+i);
                                }
                                else
                                {
                                    builder.Write(bbbb[m]);
                                    m++;
                                }
                            }
                        }
                    }
                }


                doc.Save("c://output.doc");
                tbStatus.Text = "创建成功";
            }
            catch (Exception ex)
            {
                tbMessage.Text = "创建失败" + ex.StackTrace;
                
            }

        }

        private void btnHeading_Click(object sender, EventArgs e)
        {
            tbStatus.Text = "正在创建。。。。。。";
            
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            try
            {

              

                // There are 9 levels in this list, lets try them all.
                //for (int i = 0; i < 9; i++)
                //{
                    // Create a numbered list based on one of the Microsoft Word list templates and
                    // apply it to the current paragraph in the document builder.
                    builder.ListFormat.List = doc.Lists.Add(ListTemplate.OutlineLegal);
                    builder.ListFormat.ListLevelNumber = 0;
                    builder.Writeln("LevelA " + 0);
                    // This is a way to stop list formatting. 
                    builder.ListFormat.List = null;
                    builder.Writeln("列表中的内容 " + 0);

                    //第二个编号 
                    builder.ListFormat.List = doc.Lists.Add(ListTemplate.OutlineLegal);
                    builder.ListFormat.ListLevelNumber = 1;
                    builder.Writeln("LevelA " + 1);
                    // This is a way to stop list formatting. 
                    builder.ListFormat.List = null;
                    builder.Writeln("列表中的内容 " + 1);

                    //第三个编号 
                    builder.ListFormat.List = doc.Lists.Add(ListTemplate.OutlineLegal);
                    builder.ListFormat.ListLevelNumber = 0;
                    builder.Writeln("LevelA " + 0);
                    // This is a way to stop list formatting. 
                    builder.ListFormat.List = null;
                    builder.Writeln("列表中的内容 " + 0);

                //}

                doc.Save("c://output.doc");
                tbStatus.Text = "创建成功";
            }
            catch (Exception ex)
            {
                tbStatus.Text = "创建失败" + ex.Message;
                tbMessage.Text = (ex.StackTrace);
            }
        }

        private void btnGernerateHeading_Click(object sender, EventArgs e)
        {

            tbStatus.Text = "正在创建。。。。。。";
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            try
            {
                // This truly makes the document empty. No sections (not possible in Microsoft Word).
               // doc.RemoveAllChildren();

                // Create a new section node. 
                // Note that the section has not yet been added to the document, 
                // but we have to specify the parent document.
                //Section section = new Section(doc);

                //// Append the section to the document.
                //doc.AppendChild(section);

                //// Lets set some properties for the section.
                //section.PageSetup.SectionStart = SectionStart.NewPage;
                //section.PageSetup.PaperSize = PaperSize.Letter;


                //// The section that we created is empty, lets populate it. The section needs at least the Body node.
                //Body body = new Body(doc);
                //section.AppendChild(body);


                // The body needs to have at least one paragraph.
                // Note that the paragraph has not yet been added to the document, 
                // but we have to specify the parent document.
                // The parent document is needed so the paragraph can correctly work
                // with styles and other document-wide information.
                //Paragraph para = new Paragraph(doc);
                //body.AppendChild(para);

                // We can set some formatting for the paragraph
                //para.ParagraphFormat.StyleName = "Heading 1";
                //para.ParagraphFormat.Alignment = ParagraphAlignment.Left;

               

                // So far we have one empty pararagraph in the document.
                // The document is valid and can be saved, but lets add some text before saving.
                // Create a new run of text and add it to our paragraph.
                //Run run = new Run(doc);
                //run.Text = "Hello World!";
                //run.Font.Color = System.Drawing.Color.Red;
                //para.AppendChild(run);

                //插入目录代码(TOC)
               
                builder.InsertTableOfContents("//o /"1-3/" //h //z //u");
                builder.InsertParagraph();
                
                builder.InsertBreak(BreakType.PageBreak);
                builder.InsertParagraph();


                //当前的段落
                Paragraph curParagraph = builder.CurrentParagraph;
                
                //标题2
                curParagraph.ParagraphFormat.StyleName = "Heading 2";
                //多级编号
                List list = doc.Lists.Add(ListTemplate.OutlineLegal);

                builder.ListFormat.List = list;
                builder.ListFormat.ListLevelNumber = 0;
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                builder.Writeln("第一个标题。");
                curParagraph = builder.CurrentParagraph;
                curParagraph.ParagraphFormat.StyleName = "Normal";
                builder.ListFormat.List = null;
                builder.Writeln("这是标题下的一行。");

                curParagraph = builder.CurrentParagraph;
                //设置标题2的另外一种方法
                builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
                builder.ListFormat.List = list;
                builder.ListFormat.ListLevelNumber = 0;


                builder.Writeln("第二个标题。");
                builder.ListFormat.ListLevelNumber = 1;
                curParagraph = builder.CurrentParagraph;

                builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;
                builder.Writeln("第2-1个标题。");

                curParagraph = builder.CurrentParagraph;
                curParagraph.ParagraphFormat.StyleName = "Normal";
                builder.ListFormat.List = null;
                builder.Writeln("这是标题下的一行。");


                //更新目录和页码,否则TOC代码不能更新
               
                builder.MoveToDocumentStart();
                doc.UpdateFields();

                //doc.UpdatePageLayout();
                //doc.UpdateTableLayout();

               

 

                //保存文档
                doc.Save("c://output.doc");
                tbStatus.Text = "创建成功";
            }
            catch (Exception ex)
            {
                tbStatus.Text = "创建失败" + ex.Message;
                tbMessage.Text = (ex.StackTrace);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);


            PrintDialog printDlg = new PrintDialog();

            // Initialize the print dialog with the number of pages in the document.

            printDlg.AllowSomePages = true;

            printDlg.PrinterSettings.MinimumPage = 1;

            printDlg.PrinterSettings.MaximumPage = doc.PageCount;

            printDlg.PrinterSettings.FromPage = 1;

            printDlg.PrinterSettings.ToPage = doc.PageCount;

            printDlg.ShowDialog();


        }

        private void btnFooter_Click(object sender, EventArgs e)
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            try
            {
                Section currentSection = builder.CurrentSection;
                PageSetup pageSetup = currentSection.PageSetup;

                builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
                builder.Font.Name = "Arial";
                builder.Font.Bold = true;
                builder.Font.Size = 14;


                //HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
                //HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];
                builder.Writeln("Ordinov");
                pageSetup.HeaderDistance = 20;

                //footer.Range.Replace("Ordinov", "Copyright (C) 2010 by Ordinov Ltd. Co.", false, false);

                //保存文档
                doc.Save("c://output.doc");
                tbStatus.Text = "创建成功";
            }
            catch (Exception ex)
            {
                tbStatus.Text = "创建失败:" + ex.Message;
                tbMessage.Text = (ex.StackTrace);
            }
        }

        /// <summary>
        /// 
        /// 输出文件夹结构信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFileStructure_Click(object sender, EventArgs e)
        {
            try
            {
                tbStatus.Text = "正在分析结构。。。。。。";
                //输入要分析的文件夹
                getFiles("C://test//撒旦法");
                tbMessage.Text = tbmessage;
                tbStatus.Text = "文件结构分析完毕";
            }
            catch (Exception ex)
            {
                tbStatus.Text = "创建失败:" + ex.Message;
                tbMessage.Text = (ex.StackTrace);
            }
        }

        /// <summary>
        /// 获取文件夹下的所有有关测试记录文件及目录信息
        /// </summary>
        /// <param name="folderPath"></param>
        /// 
        public void getFiles(string folderPath)
        {
            //传入的路径
            DirectoryInfo DirectoryArray = new DirectoryInfo(folderPath);

            //传入路径下直接的目录
            DirectoryInfo[] Directorys = DirectoryArray.GetDirectories();

            //传入路径下的测试目录文件夹
            DirectoryInfo directoryRecordArray = new DirectoryInfo(folderPath + "//测试记录");

            //测试目录下的文件
            FileInfo[] Files = null;

            //先输出文件
            if (directoryRecordArray.Exists == true)
            {
                //传入的目录下“测试记录”目录
               
                Files = directoryRecordArray.GetFiles();

                foreach (FileInfo inf in Files)
                {
                    if(isRightFile(inf,".rec"))
                        tbmessage += inf.FullName+ "/r/n";
                }
            }

            //输入目录
            foreach (DirectoryInfo dinf in Directorys)
            {
                //去除项目专用目录
                if (dinf.Name.Equals("测试记录") || dinf.Name.Equals("测试说明") || dinf.Name.Equals("测试追踪") || dinf.Name.Equals("问题报告"))
                    continue;

                //判断下面是否有文件(包含SubFolder的判断,只要有一个文件存在,即输出该目录)
                if(isRightFolder(dinf))
                    tbmessage += dinf.FullName + "/r/n";
                getFiles(dinf.FullName);
            }

        }

        /// <summary>
        /// 检查文件类型是否正确
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public bool isRightFile(FileInfo file,String fileSuf)
        {
            try
            {
                if (file.Name.IndexOf(fileSuf) == -1)
                    return false;
                return true;

            }
            catch (Exception ex)
            {

                tbStatus.Text = "判断文件后缀出错:" + ex.Message;
                tbMessage.Text = (ex.StackTrace);
                return false;
            }
        }

        /// <summary>
        /// 看目录下是否有文件存在,检查包含子目录
        /// </summary>
        /// <param name="dinf"></param>
        /// <returns></returns>
        public bool isRightFolder(DirectoryInfo dinf)
        {
            try
            {
                //传入的路径
                DirectoryInfo DirectoryArray = dinf;

                //传入路径下直接的目录
                DirectoryInfo[] Directorys = DirectoryArray.GetDirectories();

                //传入路径下的测试目录文件夹
                DirectoryInfo directoryRecordArray = new DirectoryInfo(dinf.FullName + "//测试记录");
             
                //测试目录下的文件
                FileInfo[] Files = null;

                //先判断当前目录下是否有文件
                if (directoryRecordArray.Exists == true)
                {
                    
                    Files = directoryRecordArray.GetFiles();

                    foreach (FileInfo inf in Files)
                    {
                        if (isRightFile(inf, ".rec"))
                            return true;
                    }
                }


                //再判断子目录下是否有文件
                foreach (DirectoryInfo df in Directorys)
                {
                    //去除项目专用目录
                    if (df.Name.Equals("测试记录") || df.Name.Equals("测试说明") || df.Name.Equals("测试追踪") || df.Name.Equals("问题报告"))
                        continue;

                    //继续判断是否有文件
                    isRightFolder(df);
                }

                return false;

            }
            catch (Exception ex)
            {

                tbStatus.Text = "判断文件后缀出错:" + ex.Message;
                tbMessage.Text = (ex.StackTrace);
                return false;
            }

        }


        /// <summary>
        /// 分析页面中的页码,前提是要在文档中把所有的Section分配好。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPages_Click(object sender, EventArgs e)
        {
            try
            {
                tbMessage.Text = "正在生成文档......"+"/r/n";
                //生成一个文档
                Document doc = new Document();
                DocumentBuilder builder = new DocumentBuilder(doc);
                Section curSection = builder.CurrentSection;

                builder.MoveToDocumentEnd();

                builder.Writeln("这是封面");
                //插入封面
                Document doctemp = new Document("c://testtemplate.doc");
                doc.AppendDocument(doctemp, ImportFormatMode.KeepSourceFormatting);
                builder.MoveToDocumentEnd();
                builder.Writeln("插入文档后");
                builder.InsertBreak(BreakType.PageBreak);
                builder.Writeln("插入分页符后");
                //插入一个连续的分节符
                builder.InsertBreak(BreakType.SectionBreakContinuous);
                builder.Writeln("插入分节符后");
                curSection = builder.CurrentSection;
                curSection.HeadersFooters.LinkToPrevious(false);
               
                //插入几个分页符
                builder.InsertBreak(BreakType.PageBreak);
                builder.Writeln("插入分页符1后");
                builder.InsertBreak(BreakType.PageBreak);
                builder.Writeln("插入分页符2后");
                builder.InsertBreak(BreakType.PageBreak);
                builder.Writeln("插入分页符3后");
                builder.InsertBreak(BreakType.PageBreak);
                builder.Writeln("插入分页符4后");
                curSection = builder.CurrentSection;

                curSection = doc.Sections[doc.Sections.Count - 1];

               
                builder.Write("Page ");
                builder.InsertField("PAGE", "");
                builder.Write(" of ");
                builder.InsertField("SECTIONPAGES", "");


                doc.UpdatePageLayout();
                doc.UpdateFields();

                tbMessage.Text += "" + "/r/n";
                tbStatus.Text = "分析页码完毕";

                //保存文档
                doc.Save("c://output.doc");
            }
            catch (Exception ex)
            {
                tbStatus.Text = "创建失败:" + ex.Message;
                tbMessage.Text = (ex.StackTrace);
            }
        }


    }
}

 

posted @ 2014-06-24 10:50  冰封的心  阅读(904)  评论(0)    收藏  举报