我已经使用我的c#程序替换了一些docx文本,并且我希望指定与原始文档具有相同样式的文档正文。我很难做到这一点。如何分配内部文本。我想要做的是body.InnerText =结果并打开文档并查看我的更改。当前当我这样做时,没有对文档进行任何更改。请帮忙!
using (var document = WordprocessingDocument.Open(path_dest, true))
{
var main = document.MainDocumentPart;
var body = main.Document.Body;
var XDoc = document.MainDocumentPart.GetXDocument();
string innertext = body.InnerText;
string innerXml = body.InnerXml;
// richTextBox1.Text = innertext;
MatchCollection matches = Regex.Matches(innertext, regex.ToString());
foreach (Match m in matches)
{
if (m.Success)
{
// MessageBox.Show(m.Value.ToString());
}
}
string result = Regex.Replace(innertext, regex.ToString(), replace_text);
Body NEWbody = body;
Paragraph para = NEWbody.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(result));
NEWbody.InnerXml = innerXml;
main.Document.RemoveChild<Body>(body);
main.Document.AppendChild<Body>(NEWbody);
/// NEWbody.InnerText = result;
document.Save();
document.Close();
更新了尝试:新结果是格式全部丢失,并且它作为一个非常大的段落出现
using (var document = WordprocessingDocument.Open(path_dest, true))
{
var main = document.MainDocumentPart;
var body = main.Document.Body;
var XDoc = document.MainDocumentPart.GetXDocument();
string innertext = body.InnerText;
string innerXml = body.InnerXml;
// richTextBox1.Text = innertext;
MatchCollection matches = Regex.Matches(innertext, regex.ToString());
foreach (Match m in matches)
{
if (m.Success)
{
// MessageBox.Show(m.Value.ToString());
}
}
string result = Regex.Replace(innertext, regex.ToString(), replace_text);
string resultmod = Regex.Replace(innerXml, regex.ToString(), replace_text);
/// main.Document.Body.InnerXml = resultmod;
Body NEWbody = new Body();
// NEWbody.InnerXml = resultmod;
Paragraph para = NEWbody.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(result));
main.Document.RemoveAllChildren();
main.Document.RemoveAllChildren<Body>();
main.Document.RemoveAllChildren<Run>();
main.Document.AppendChild<Body>(NEWbody);
// NEWbody.InnerText = result;
document.MainDocumentPart.Document.Save();
richTextBox1.Text = main.Document.Body.InnerXml;
document.Close();
我尝试使用openxml的电动工具。我使用TextReplacer,但不允许使用正则表达式。我无法让OpenXmlRegex工作
using (WordprocessingDocument doc = WordprocessingDocument.Open(wfile, true))
{
//attempt using TextReplacer
TextReplacer.SearchAndReplace(doc, regex1.ToString(), replace_text1, false);
// MessageBox.Show(doc.MainDocumentPart.Document.Body.InnerText);
doc.MainDocumentPart.Document.Save();
//attempt using OpenXmlRegex
var XDoc = doc.MainDocumentPart.GetXDocument();
//tried on one paragraph that didnt work either // IEnumerable<XElement> content = XDoc.Descendants(W.p).Take(1);
IEnumerable<XElement> content = XDoc.Descendants(W.Body);
OpenXmlPowerTools.OpenXmlRegex.Replace(content, regex, replace_text, null);
}