取文件

    技术2022-07-05  217

    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);            }        }

        }}


    最新回复(0)