我正在嘗試搜索某個特定文本的Word文檔,然後將其替換爲自定義表格。我似乎幾乎有它的工作,但它似乎增加了前一個詞的一半,而不是在它找到文本的位置。在Word文檔中查找文本並將其替換爲表格
這是我的功能
public void AddTableAtCursor(string tabledata,
string find,
Boolean flh = true,
string name = "Table")
{
object replaceAll = Word.WdReplace.wdReplaceAll;
Word.Range srng = Application.ActiveDocument.Content;
srng.WholeStory();
srng.Find.ClearFormatting();
srng.Find.Text = find;
srng.Find.Replacement.ClearFormatting();
srng.Find.Replacement.Text = "";
int FirstChr = srng.Text.IndexOf(find);
if (FirstChr != -1)
{
Word.Range ts =
Application.ActiveDocument.Range(FirstChr, FirstChr);
this.Application.Selection.TypeParagraph();
srng.Find.Execute(
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref replaceAll, ref missing,
ref missing, ref missing, ref missing);
string[] rows = tabledata.Split('|');
string[] c = rows[0].Split('^');
rows[0] = null;
object styleName = "Light List - Accent 1";
Word.Table tbl = null;
Word.Range currentSelection = srng;
int hclen = c.Length;
if (TomData.IndPrices != "on") { hclen = hclen - 2; }
tbl = Application.ActiveDocument.Content.Tables.Add(
ts, rows.Length + 1, hclen);
tbl.set_Style(ref styleName);
tbl.PreferredWidth = 90;
tbl.PreferredWidthType =
Word.WdPreferredWidthType.wdPreferredWidthPercent;
// First Row, Put the name into the first cell
for (int i = 1; i <= hclen; i++)
{
if (i == 1)
{
tbl.Cell(1, i).Range.InsertBefore(name);
}
else
{
tbl.Cell(1, i).Range.InsertBefore("");
}
}
// 2nd row, put the headers in
for (int i = 1; i <= hclen; i++)
{
int t = i - 1;
tbl.Cell(2, i).Range.InsertBefore(c[t]);
}
int tblrow = 3;
// after that just put the data
for (int rc = 0; rc < rows.Length; rc++)
{
if (rows[rc] != null)
{
string[] coldata = rows[rc].Split('^');
int tblcol = 1;
int clen = coldata.Length;
if (TomData.IndPrices != "on") { clen = clen - 2; }
for (int nc = 0; nc < clen; nc++)
{
tbl.Cell(tblrow, tblcol).Range.InsertBefore(
coldata[nc]);
tblcol++;
}
tblrow++;
}
}
}
}
我在做什麼錯?