gpt4 book ai didi

c# - 在c#中从word文档中获取替换普通文本

转载 作者:行者123 更新时间:2023-11-30 22:33:44 25 4
gpt4 key购买 nike

我正在将我的应用程序中的一些数据插入到 word 文档中,然后再次保存。我现在拥有的代码对于放在 word 文档中的表格中的文本可以正常工作,但它不会获取不在表格中的文本。例如,word 文档的第 1 页不在表格中,代码会跳过第 1 页并立即转到第 2 页,其中表格中有文本,它会按原样替换文本。这是我的代码:

Document docc = app.Documents.Open(ref path, ref o, ref readOnly, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
docc.Activate();
try
{
foreach (Paragraph p in docc.Paragraphs)
{
Range rng = p.Range;
Style sty = (Style)p.get_Style();

if ((bool)rng.get_Information(WdInformation.wdWithInTable) == true)
{
foreach (Cell c in rng.Cells)
{
if (rng.Cells.Count > 0)
{
string testtt = c.Range.Text.ToString();
if (c.Range.Text.ToString().Contains("[Company_Name]\r\a"))
// c.Next.Range.Text = "Sacramento";
c.Range.Text = "Sacramento";
}
}
docc.Save();
}
docc.Close(ref o, ref o, ref o);
}
}

我知道这一行:

 if ((bool)rng.get_Information(WdInformation.wdWithInTable) == true)

仅获取包含表格的页面,但我想知道如何从没有表格的页面获取数据并修改那里的文本。

最佳答案

首先,您在更改每个单元格后保存文档 - 没有必要这样做。其次,更重要的是,您要在第一段之后关闭文档,这样下一段(段落)就会抛出异常。

我建议使用类似休闲代码的代码,它将所有出现的“[Company_Name]”替换为“Sacramento”(在整个文档中)。

using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Runtime.InteropServices;

...

object o = Missing.Value;
object oFalse = false;
object oTrue = true;

Word._Application app = null;
Word.Documents docs = null;
Word.Document doc = null;

object path = @"C:\path\file.doc";

try
{
app = new Word.Application();
app.Visible = false;
app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

docs = app.Documents;
doc = docs.Open(ref path, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
doc.Activate();

foreach (Word.Range range in doc.StoryRanges)
{
Word.Find find = range.Find;
object findText = "[Company_Name]";
object replacText = "Sacramento";
object replace = Word.WdReplace.wdReplaceAll;
object findWrap = Word.WdFindWrap.wdFindContinue;

find.Execute(ref findText, ref o, ref o, ref o, ref oFalse, ref o,
ref o, ref findWrap, ref o, ref replacText,
ref replace, ref o, ref o, ref o, ref o);

Marshal.FinalReleaseComObject(find);
Marshal.FinalReleaseComObject(range);
}

doc.Save();
((Word._Document)doc).Close(ref o, ref o, ref o);
app.Quit(ref o, ref o, ref o);
}
finally
{
if (doc != null)
Marshal.FinalReleaseComObject(doc);

if (docs != null)
Marshal.FinalReleaseComObject(docs);

if (app != null)
Marshal.FinalReleaseComObject(app);
}

有两点很重要:

1) 不要对 COM 对象使用两个点:

// might be a problem soon:
app.Documents.Open(....

// better way:
Documents docs = app.Documents;
Document doc = docs.Open(...

2) 在不需要它们时以相反的顺序释放它们:

if (doc != null)
Marshal.FinalReleaseComObject(doc);

if (docs != null)
Marshal.FinalReleaseComObject(docs);

关于c# - 在c#中从word文档中获取替换普通文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8156719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com