您如何使用 interop.word 查找并替换到列表中?

How do you find and replace into list using interop.word?

所以我正在尝试将用于将某些独特句子替换为每种类型 checkedbox.checked 的列表的代码放在一起,例如:

"uniquecode1" 变成:

我设法使用了 c# word interop find and replace everything 中的简单查找和替换方法 但我仍然没有找到将它们转换为列表项的方法。 有那么一刻我在想为什么我不这样做呢?

for (int i = 0; i == checkedbox.Count; i++)
            {
                FindAndReplace(oWord, "uniquecode1", checkedbox[i]);
            }

然后我意识到,一旦 "uniquecode1" 消失,它几乎就失败了。如果有人能给我一个答案或至少一个线索,我真的很感激。 这是我当前的代码,我知道它很脏...

string[] Mycollection = new string[] { "One, Two, Three" };
            string temp;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "pdf files (*.pdf)|*.pdf";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.ShowDialog();
            temp = saveFileDialog1.FileName;

            // Create an instance of Word.exe
            Microsoft.Office.Interop.Word.Application oWord = new Word.Application
            {
                // To make this instance of word invisible (Can still see it in the taskmgr).
                Visible = false
            };

            // Interop requires objects.
            object oMissing = System.Reflection.Missing.Value;
            object isVisible = true;
            object readOnly = true;     // Does not cause any word dialog to show up
            //object readOnly = false;  // Causes a word object dialog to show at the end of the conversion
            object oInput = textBox1.Text;
            object oOutput = temp;
            object oFormat = WdSaveFormat.wdFormatPDF;

            // Load a document into our instance of word.exe
            Document oDoc = oWord.Documents.Open(
                ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing
                );

            // Make this document the active document.
            oDoc.Activate();
            //Replace Text1
            FindAndReplace(oWord, "<Input Module1>", richTextBox1.Text);
            //Replace Text to List1
            foreach(string lisText in Mycollection)
            {
                //program to convert Text into a bullet or number list
            }

                // Save this document using Word
                oDoc.SaveAs(ref oOutput, ref oFormat, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing
                );

            // Always close Word.exe.
            oWord.Quit(ref oMissing, ref oMissing, ref oMissing);

根据他们使用的 Sauntinsoft

string loadPath = @"..\..\example.docx";

            DocumentCore dc = DocumentCore.Load(loadPath);
            string[] myCollection = new string[] { "One", "Two", "Three", "Four", "Five" };

            ListStyle bullList = new ListStyle("Bullets", ListTemplateType.Bullet);
            dc.Styles.Add(bullList);
            int level = 0;

            List<Paragraph> parList = new List<Paragraph>();


            foreach (string listText in myCollection)
            {
                Paragraph p = new Paragraph(dc);
                p.Content.End.Insert(listText, new CharacterFormat() { Size = 14.0, FontColor = Color.Black });
                p.ListFormat.Style = bullList;
                p.ListFormat.ListLevelNumber = level;
                p.ParagraphFormat.SpaceAfter = 0;
                parList.Add(p);
            }

            Regex regex = new Regex(@"Hello", RegexOptions.IgnoreCase);


            foreach (ContentRange item in dc.Content.Find(regex).Reverse())
            {
                foreach (Paragraph p in parList.Reverse<Paragraph>())
                    item.End.Insert(p.Content);               
            }

            foreach (ContentRange item in dc.Content.Find(regex).Reverse())
            {
                item.Delete();
            }
            string savePath = Path.ChangeExtension(loadPath, ".replaced.docx");
            dc.Save(savePath, SaveOptions.DocxDefault);

            // Open the original and result documents for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(loadPath) { UseShellExecute = true });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(savePath) { UseShellExecute = true });

使用互操作执行它是一个多步骤过程。首先需要找到目标——被搜索的文本。然后将信息插入 Range,最后格式化它。

Word 的 Find.Execute returns 一个布尔值 - 成功时它是 true 并且 Find 是 运行 的 Range 在找到位置。因此,将文本 添加到 Range,然后格式化 Range,如示例代码中所示 *:

Word.Document doc = wdApp.ActiveDocument;
//Code from question
//Document oDoc = oWord.Documents.Open(
//            ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing,
//            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
//            ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

Word.Range rng = doc.Content;
Word.Find f = rng.Find;
object oTrue = true;
object missing = Type.Missing;

string searchTerm = "uniquecode1";

f.ClearFormatting();
f.Text = searchTerm;
bool found = f.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, Word.WdFindWrap.wdFindStop, ref missing, ref missing, Word.WdReplace.wdReplaceNone,
    ref  missing, ref missing, ref missing, ref missing);
if (found)
{
    rng.Delete();
    //Code from question
    //for (int i = 0; i == checkedbox.Count; i++)
    List<string> lst = new List<string> { "one", "two", "three" };
    foreach (string entry in lst)
    {
        rng.InsertAfter(entry + "\n");
    }
    rng.ListFormat.ApplyBulletDefault();
}

* 鉴于我在问题中理解的要求,这可以完全使用 Find & Replace if:

  • Replacement.Text可以是一串。在此示例中,可以通过将所有值连接到一个字符串 beforeFind 并将该字符串分配给 f.Replacement.Text 来实现。那么参数 Word.WdReplace.wdReplaceNone 将是 wdReplaceOne.
  • bullets/numbering 定义为命名样式。这将需要文档(或由代码动态生成)中的 段落样式 链接到定义 ListTemplate 对象项目符号 and/or 编号。假设存在,可以将样式分配给 Replacement.set_Style("stylename");,然后需要将参数 Format 设置为 true.

这基本上就是您不想为之付费的图书馆在幕后发生的事情。