C# 在Spire.Doc中插入HTML而不是Template.docx中的键
我想使用Spire.Doc从C# 在Spire.Doc中插入HTML而不是Template.docx中的键,c#,html,ms-word,spire.doc,C#,Html,Ms Word,Spire.doc,我想使用Spire.Doc从Template.docx创建Word文档。为此,我编写了如下代码: //sample file path string samplePath = Application.StartupPath + Path.DirectorySeparatorChar + "Template.docx"; //result docs paths string docxPath = Application.StartupPath + Path.DirectorySeparatorCh
Template.docx
创建Word文档。为此,我编写了如下代码:
//sample file path
string samplePath = Application.StartupPath + Path.DirectorySeparatorChar + "Template.docx";
//result docs paths
string docxPath = Application.StartupPath + Path.DirectorySeparatorChar + "Result.docx";
Lorem ipsum <b>dolor sit amet</b>, consectetur <i>adipiscing</i> elit.
按钮提交事件:
private void btnSubmit_Click(object sender, EventArgs e)
{
//initialize word object
document = new Document();
document.LoadFromFile(samplePath);
//get strings to replace
Dictionary<string, string> dictReplace = GetReplaceDictionary();
//Replace text
foreach (KeyValuePair<string, string> kvp in dictReplace)
{
document.Replace(kvp.Key, kvp.Value, true, true);
}
//Save doc file.
document.SaveToFile(docxPath, FileFormat.Docx);
document.Close();
}
我想这样写“工作经验”文本框:
//sample file path
string samplePath = Application.StartupPath + Path.DirectorySeparatorChar + "Template.docx";
//result docs paths
string docxPath = Application.StartupPath + Path.DirectorySeparatorChar + "Result.docx";
Lorem ipsum <b>dolor sit amet</b>, consectetur <i>adipiscing</i> elit.
Lorem ipsum door sit amet,一位杰出的领导者。
屏幕如下:
我想在word文档中用粗体显示dolor sit amet,用斜体显示adivising,如下所示:
但不幸的是,HTML标记在Word文档中显示如下:
这是我的模板.docx
文件:
如何正确显示HTML文本而不是
#experience#
variable?不幸的是,据我所知,使用Spire并不是一种简单的方法。document.Replace只是将一个字符串替换为您已经发现的另一个字符串。《Spire计划指南》确实提出了一种新的设计方案,但并不特别优雅
对于要替换的文本,您需要在模板文档中添加书签。因此,如果选择文本“体验”,并将其添加为名为“体验”的书签:
然后,您可以使用下面的函数将文本替换为提供的html:
public void ReplaceBookmarkHTML(Document doc, string bookmarkName, string htmlString)
{
Section tempSection = doc.AddSection();
tempSection.AddParagraph().AppendHTML(htmlString);
ParagraphBase replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
ParagraphBase replacementLastItem = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
TextBodySelection selection = new TextBodySelection(replacementFirstItem, replacementLastItem);
TextBodyPart part = new TextBodyPart(selection);
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
bookmarkNavigator.MoveToBookmark(bookmarkName);
bookmarkNavigator.ReplaceBookmarkContent(part);
doc.Sections.Remove(tempSection);
}
然后,您可以像下面这样调用它,以使您的HTML替换书签:
ReplaceBookmarkHTML(document, "experience", "Lorem ipsum <b>dolor sit amet</b>, consectetur <i>adipiscing</i> elit.");
ReplaceBookmarkHTML(文档,“经验”,“知识产权”或“知识产权”或“知识产权精英”);
今天早上我找到了一个很好的解决方案。非常感谢你。