我有一个请求,要根据提供给我的模板即时创建一个 word 文档。我做了一些研究,一切似乎都指向 OpenXML。我已经对此进行了调查,但是创建的 cs 文件超过 15k 行并且破坏了我的 VS 2010(导致它在我每次进行更改时都没有响应)。
我一直在看这个关于 Open XML 的教程系列 http://openxmldeveloper.org/blog/b/openxmldeveloper/archive/2011/10/13/getting-started-with-open-xml-development.aspx
我过去曾用文本文件和正则表达式做过一些事情,但由于 Word 对所有内容进行了加密,所以这行不通。对于从模板创建 Word 文档,是否有任何其他相当轻量级的选项。
请您参考如下方法:
//嗨,这很简单。
//First, you should copy your Template file into another location.
string SourcePath = "C:\\MyTemplate.dotx";
string DestPath = "C:\\MyDocument.docx";
System.IO.File.Copy(SourcePath, DestPath);
//After copying the file, you can open a WordprocessingDocument using your Destination Path.
WordprocessingDocument Mydoc = WordprocessingDocument.Open(DestPath, true);
//After openning your document, you can change type of your document after adding additional parts into your document.
mydoc.ChangeDocumentType(WordprocessingDocumentType.Document);
//If you wish, you can edit your document
AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "MyRelationID" };
MainDocumentPart mainPart = mydoc.MainDocumentPart;
MySettingsPart = mainPart.DocumentSettingsPart;
MySettingsPart.Settings.Append(attachedTemplate1);
MySettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(CopyPath, UriKind.Absolute), "MyRelationID");
//Finally you can save your document.
mainPart.Document.Save();
