【发布时间】:2018-06-09 07:14:24
【问题描述】:
我正在尝试使用 C# 的 OpenXML altchunk 方法将 HTML 内容添加到 DOCX 文件。下面的示例代码工作正常,并将 HTML 内容附加到文档的末尾。我的要求是在文档中的特定位置添加 HTML 内容,例如在表格单元格内或段落内,或者搜索特定字符串并将其替换为 HTML 字符串或使用内容控件标记的占位符。您能否指点我一些示例或分享一些建议。如果您需要更多信息,请告诉我。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using OpenXmlPowerTools;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using System.Xml;
namespace Docg2
{
class Program
{
static void Main(string[] args)
{
testaltchunk();
}
public static void testaltchunk()
{
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
using (WordprocessingDocument myDoc = WordprocessingDocument.Open("../../Test3.docx", true))
{
string html =
@"<html>
<head/>
<body>
<h1>Html Heading</h1>
<p>This is an html document in a string literal.</p>
</body>
</html>";
string altChunkId = "AltChunkId1";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart("application/xhtml+xml", altChunkId);
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
using (StreamWriter stringStream = new StreamWriter(chunkStream))
stringStream.Write(html);
XElement altChunk = new XElement(w + "altChunk", new XAttribute(r + "id", altChunkId));
XDocument mainDocumentXDoc = GetXDocument(myDoc);
mainDocumentXDoc.Root
.Element(w + "body")
.Elements(w + "p")
.Last()
.AddAfterSelf(altChunk);
SaveXDocument(myDoc, mainDocumentXDoc);
}
}
private static void SaveXDocument(WordprocessingDocument myDoc, XDocument mainDocumentXDoc)
{
// Serialize the XDocument back into the part
using (var str = myDoc.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write))
using (var xw = XmlWriter.Create(str))
mainDocumentXDoc.Save(xw);
}
private static XDocument GetXDocument(WordprocessingDocument myDoc)
{
// Load the main document part into an XDocument
XDocument mainDocumentXDoc;
using (var str = myDoc.MainDocumentPart.GetStream())
using (var xr = XmlReader.Create(str))
mainDocumentXDoc = XDocument.Load(xr);
return mainDocumentXDoc;
}
}
}
【问题讨论】:
-
如果您坚持像这里一样直接操作 XML(而不是使用 OpenXML api),那么将其视为常规 XML 文档并像现在一样在任何您想要的地方插入您的元素。如果您选择使用 OpenXML api,那么您将能够 much more advanced searching,并插入 AltChunk 而不是插入
XElement。
标签: c# html openxml docx openxml-table