我有这个代码搜索文本并用MS Word文档中的另一个文本替换它。我想做类似的操作。找到文本并将其替换为图像。我可以传递文件位置,图像位置。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
//using System.Drawing;
namespace WritingIntoDocx
{
[ComVisible(true)]
public interface IMyClass
{
void DocumentDigitalSign(string filep,string findt,string replacet);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Program : IMyClass
{
public void DocumentDigitalSign(string filep, string findt, string replacet)
{
string filepath = filep;
string Findtext = findt;
string ReplaceText = replacet;
word.Application app = new word.Application();
word.Document doc = app.Documents.Open(filepath);
word.Range myStoryRange = doc.Range();
//First search the main document using the Selection
word.Find myFind = myStoryRange.Find;
myFind.Text = Findtext;
myFind.Replacement.Text = ReplaceText;
//myFind.Replacement.
myFind.Forward = true;
myFind.Wrap = word.WdFindWrap.wdFindContinue;
myFind.Format = false;
myFind.MatchCase = false;
myFind.MatchWholeWord = false;
myFind.MatchWildcards = false;
myFind.MatchSoundsLike = false;
myFind.MatchAllWordForms = false;
myFind.Execute(Replace: word.WdReplace.wdReplaceAll);
//'Now search all other stories using Ranges
foreach (word.Range otherStoryRange in doc.StoryRanges)
{
if (otherStoryRange.StoryType != word.WdStoryType.wdMainTextStory)
{
word.Find myOtherFind = otherStoryRange.Find;
myOtherFind.Text = Findtext;
myOtherFind.Replacement.Text = ReplaceText;
myOtherFind.Wrap = word.WdFindWrap.wdFindContinue;
myOtherFind.Execute(Replace: word.WdReplace.wdReplaceAll);
}
// 'Now search all next stories of other stories (doc.storyRanges dont seem to cascades in sub story)
word.Range nextStoryRange = otherStoryRange.NextStoryRange;
while (nextStoryRange != null)
{
word.Find myNextStoryFind = nextStoryRange.Find;
myNextStoryFind.Text = Findtext;
myNextStoryFind.Replacement.Text = ReplaceText;
myNextStoryFind.Wrap = word.WdFindWrap.wdFindContinue;
myNextStoryFind.Execute(Replace: word.WdReplace.wdReplaceAll);
nextStoryRange = nextStoryRange.NextStoryRange;
}
}
app.Documents.Save();
app.Documents.Close();
}
}
}
答案 0 :(得分:1)
我认为你可以尝试这样的事情:
var doc = app.Documents.add(path.GetFullPath(@"Docs/yourDoc.docx")), visible: false);
doc.Activate();
String textToReplace = "your text";
var selected = app.Selection;
selected.Text = string.Format("[{0}]", keyword);
selected.Find.Execute(Replace: WdReplace.wdReplaceNone);
selected.Range.Select();
var imgPath = Path.GetFullPath(string.Format(yourImage))
selected.InLineShapes.AddPicture(FileName: imgPath, LinkToFile: false, SaveWithDocument: true);
doc.SaveAs(path.GetFullPath(@"Docs/yourDoc.docx"));