为了实现在WORD中添加文本和图片,在网上找了一下,找到了一些资源,自己组织了一下,形成一个简单的类,一些方法是利用模板的,一些是不用的。运行时,将弹出WORD窗口。
class WordUtil
{
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc"; /**//* \endofdoc is a predefined bookmark */
Word._Application oWord = null;
Word._Document oDoc = null;
public WordUtil()
{
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
}
public WordUtil(string templateFile)
{
oWord = new Word.Application();
oWord.Visible = true;
object oTemplate = templateFile;
oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
}
public void addTxt(string txt)
{
Word.Paragraph oPara;
object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara = oDoc.Content.Paragraphs.Add(ref oRng);
oPara.Range.Text = txt;
oPara.Format.SpaceAfter = 6;
oPara.Range.InsertParagraphAfter();
}
public void addTxt(string bookMark, string txt)
{
object oBookMark = bookMark;
oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = txt;
}
public void addPicture(string fileName, float width, float height)
{
Word.Paragraph oPara;
object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara = oDoc.Content.Paragraphs.Add(ref oRng);
Word.InlineShape shape = oPara.Range.InlineShapes.AddPicture(fileName, ref oMissing, ref oMissing, ref oMissing);
shape.Width = oWord.InchesToPoints(width);
shape.Height = oWord.InchesToPoints(height);
oPara.Format.SpaceAfter = 6;
oPara.Range.InsertParagraphAfter();
}
public void addPicture(string bookMark, string fileName, float width, float height)
{
object oBookMark = bookMark;
Word.InlineShape shape = oDoc.Bookmarks.get_Item(ref oBookMark).Range.InlineShapes.AddPicture(fileName, ref oMissing, ref oMissing, ref oMissing);
shape.Width = oWord.InchesToPoints(width);
shape.Height = oWord.InchesToPoints(height);
}
}
例子:
WordUtil wt = new WordUtil(@"c:\temp.dot");
wt.addTxt("SOA_CUSTOM", "您好");
wt.addTxt("SOA_EOTITLE", "hello the world");
wt.addPicture("SOA_EOTYPE", @"D:\MyPrograms\BMP\img12.jpg", 2f, 1.5f);
wt.addTxt("SOA_EOREASON", "测试");
效果:
在此也非常感谢网上网友的无私共享。