本文将以“Step by Step”的方式演示如何创建一个最简单的使用Open XML API的应用程序。我们假设读者已经熟悉了Visual Studio 2005/2008的基本操作,并且有基础C#语言知识。
本次实验需要用到的软件:
1. Visual Studio 2005 或者 Visual Studio 2008 (Beta 2)
2. Word 2007
3. .NET Framework 3.0
4. Open XML SDK (CTP)
第一步:创建一个C#控制台应用程序。命名为OpenXML1。
第二步:在项目中添加对下列程序集的引用。
· WindowsBase(版本:3.0.0.0)
· Microsoft.Office.DocumentFormat.OpenXml(版本:1.0.531.0)
第三步:打开Program.cs文件,添加对Open XML API Namespace的引用以及对System.Diagnostics的引用:
using Microsoft.Office.DocumentFormat.OpenXml.Packaging;
using System.Diagnostics;
第四步:在Class Program内定义两个常量备用:
private const string DocPath = "test.docx";
private const string docXml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""><w:body><w:p><w:r><w:t>Hello world!</w:t></w:r></w:p></w:body></w:document>";
第五步:在Main方法内输入下列代码:
WordprocessingDocument docx = WordprocessingDocument.Create(DocPath, WordprocessingDocumentType.Document);
docx.AddMainDocumentPart();
Stream s = docx.MainDocumentPart.GetStream();
byte[] buffer = new UTF8Encoding(false).GetBytes(docXml);
s.Write(buffer, 0, buffer.GetLength(0));
docx.Close();
Process.Start(DocPath);
第六步:运行这个控制台程序,我们可以看到Word打开了程序通过Open XML API创建的test.docx文件。文档的内容是古老的“Hello world!”。
至此,一个简单的Open XML API实验就完成了。

本文通过步骤演示如何使用C#和Open XML SDK创建一个简单的Word文档。首先,创建C#控制台应用并添加所需引用,然后定义文档路径和XML内容,最后使用Open XML API写入XML数据到Word文档,生成的文档显示'Hello world!'。
2405

被折叠的 条评论
为什么被折叠?



