是否有可能插入RTF文本块放入使用的OpenXML一个Word文档(.docx)? [英] Is it possible to insert pieces of RTF text into a Word document (.docx) using OpenXml?
问题描述
我正在开发一个.NET的C#应用程序,需要创建一个Word文档,插入它们存储在数据库中的RTF文本片段。有谁知道这是可能的,这是如何使用的OpenXML(或COM互操作)做了什么?
I'm developing a .NET C# app that needs to create a Word document, inserting fragments of RTF text which are stored in a database. Does anyone know if it is possible and how this is done using OpenXml (or COM interop)?
我并不需要将一个完整的RTF文件插入Word文档。我需要以编程方式创建一个Word文档,在Word文档中不同的地方使用C#添加RTF文本片段。
I don't need to convert one complete RTF file into a Word document. I need to programatically create a Word document and add pieces of RTF text in different places in the word document using C#.
推荐答案
您可以导入通过的 altChunk 的锚外部内容。 在 altChunk 的锚定义在一个word文档的地方插入 外部内容,如RTF,HTML,XML,...
You can import external content via the altChunk anchor. The altChunk anchor defines a place within a word document to insert external content such as RTF, HTML, XML, ...
有关的 altChunk 的锚,请参阅更多信息 下面的<一个href="http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.altchunk%28v=office.15%29.aspx">MSDN文章
For more information about the altChunk anchor please refer to the following MSDN article.
下面code说明如何使用插入RTF一大块成word文档 OpenXML的SDK:
The following code shows how to insert a chunk of RTF into a word document using the OpenXML SDK:
- 打开Word文档。
- 创建一个
AlternativeFormatImportPart
块具有唯一一个ID。 - 订阅您的RTF数据成块(我使用
的MemoryStream
点击这里)。 - 创建一个
AltChunk
与用于创建AlternativeFormatImportPart
。 相同的ID
- 保存的Word文档。
- Open your word document.
- Create an
AlternativeFormatImportPart
chunk with a unique chunk ID. - Feed your RTF data into the chunk (I'm using a
MemoryStream
here). - Create an
AltChunk
with the same ID used to create theAlternativeFormatImportPart
. - Save the word document.
。
static void Main(string[] args)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(@"test.docx", true))
{
string altChunkId = "AltChunkId5";
MainDocumentPart mainDocPart = doc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.Rtf, altChunkId);
string rtfEncodedString = @"{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard This is some {\b bold} text.\par}";
using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(val)))
{
chunk.FeedData(ms);
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainDocPart.Document.Body.InsertAfter(
altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last());
mainDocPart.Document.Save();
}
}
这篇关于是否有可能插入RTF文本块放入使用的OpenXML一个Word文档(.docx)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!