我有一个用于获取文本的 HtmlEditor 。 (
第一段。
块引用中的段落。第二段。
)我想将 html 插入到 word 中。我使用 open xml 但不起作用。
void ConvertHTML(string htmlFileName, string docFileName)
{
// Create a Wordprocessing document.
using (WordprocessingDocument package = WordprocessingDocument.Create(docFileName, WordprocessingDocumentType.Document))
{
// Add a new main document part.
package.AddMainDocumentPart();
// Create the Document DOM.
package.MainDocumentPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(new Body());
Body body = package.MainDocumentPart.Document.Body;
XPathDocument htmlDoc = new XPathDocument(htmlFileName);
XPathNavigator navigator = htmlDoc.CreateNavigator();
XmlNamespaceManager mngr = new XmlNamespaceManager(navigator.NameTable);
mngr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");
XPathNodeIterator ni = navigator.Select("html");
while (ni.MoveNext())
{
body.AppendChild<Paragraph>(new Paragraph(new Run(new Text(ni.Current.Value))));
}
// Save changes to the main document part.
package.MainDocumentPart.Document.Save();
}
}
编辑
public static void ConvertHTML(string htmlFilePath, string wordFilePath)
{
//Read HTML file content
string HTML = File.ReadAllText(htmlFilePath);
using WordprocessingDocument wordDocument = WordprocessingDocument.Create(wordFilePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
// Add a new main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = new();
mainPart.Document.Append(body);
//Write HTML content
Paragraph paragraph = new();
Run run = new();
run.Append(new Text(HTML));
paragraph.Append(run);
body.Append(paragraph);
//Save the document
mainPart.Document.Save();
}