為了實現在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", "測試");
?
效果:
?
在此也非常感謝網上網友的無私共享。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
