我试图改变使用C#和字自动化在Word文档中的文字和图片。 我有它的文本,我做类似下面的代码段工作正常,但我甚至不知道如何开始更换图像。
任何帮助是极大的赞赏!
奥利弗
using Microsoft.Office.Interop.Word;
...
private static Application WordApp;
private static object missing = System.Reflection.Missing.Value;
private static object yes = true;
private static object no = false;
...
object search;
object replace;
object replaceAll =
Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
object filename = SourceFile;
object destination = DestinationFile;
Document d = WordApp.Documents.Open(
ref filename, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing);
d.Activate();
search = "OLDSTRING";
replace = "NEWSTRING";
WordApp.Selection.Find.Execute(
ref search, ref yes, ref yes, ref no, ref no, ref no, ref yes,
ref missing, ref missing, ref replace, ref replaceAll,
ref missing, ref yes, ref missing, ref missing);
你可以通过InlineShapes循环和更换图片
using System.Collections.Generic;
using Word = Microsoft.Office.Interop.Word;
namespace WordExample
{
class WordExample
{
#region Constructor
public WordExample()
{
WordApp = new Microsoft.Office.Interop.Word.Application();
}
#endregion
#region Fields
private Word.Application WordApp;
private object missing = System.Reflection.Missing.Value;
private object yes = true;
private object no = false;
private Word.Document d;
private object filename = @"C:\FullPathToFile\example.doc";
#endregion
#region Methods
public void UpdateDoc()
{
d = WordApp.Documents.Open(ref filename, ref missing, ref no, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref yes, ref missing, ref missing, ref missing, ref missing);
List<Word.Range> ranges = new List<Microsoft.Office.Interop.Word.Range>();
foreach (Word.InlineShape s in d.InlineShapes)
{
if (s.Type == Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapePicture)
{
ranges.Add(s.Range);
s.Delete();
}
}
foreach (Word.Range r in ranges)
{
r.InlineShapes.AddPicture(@"c:\PathToNewImage\Image.jpg", ref missing, ref missing, ref missing);
}
WordApp.Quit(ref yes, ref missing, ref missing);
}
#endregion
}
}