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

 

posted @ 2015-02-05 14:19  冰封的心  阅读(3047)  评论(0)    收藏  举报