ruby调用OLE实现word输出(支持嵌入图片)

由于项目的需要,要实现ruby生成word报告。而且,要求能嵌入图片。
RTF和PDF,ruby都已经有开源的实现了,但是在github上面找到的都是要求ruby版本在1.8.7之上,
而我们的自动化框架还在1.8.6,所以,都不能使用。
word OLE在哪里去搜索参数列表啊。。。貌似网上都找不到详细的。这个挺悲剧的。
有知道的朋友可以PM我一下,多谢。。。
嵌入图片有两种函数,后来使用了第二种:
ad.Shapes.AddPicture(picture_360.to_s,false,true,left,top,width,height)
sel.InlineShapes.AddPicture(picture_360.to_s,false,true,nil)
经过网上搜索加以整理,最终实现了,代码如下:

# coding: utf-8
require 'win32ole'

root = File.expand_path(File.dirname(__FILE__) )
pic_root = root + "/pics"
start = Time.now
filename = root+"/virus_scan_reports_"+start.to_i().to_s()+".doc"

puts(root+",time:"+start.to_i().to_s())

def word_report(report_filename,pic_hash,scantitle="")
word=WIN32OLE.new 'word.Application'
word.visible=false
doc=word.Documents
d=doc.add
sel=word.Selection
ad=word.ActiveDocument

ad.Styles.Add('Name'=>'title')
font=ad.Styles("title").Font
font.Size=20
font.Bold=true
font.Name="宋体"

ad.Styles.Add('Name'=>'content')
font=ad.Styles("content").Font
font.Size=12
font.Bold=false
font.Name="宋体"

sel.Style=ad.Styles("title")
sel.typeText("杀毒报告:#{scantitle}")

sel.TypeParagraph;
sel.Style=ad.Styles("content")

picture_360 = pic_hash[:picture_360]
picture_macaffee = pic_hash[:picture_macaffee]
picture_trend = pic_hash[:picture_trend]
picture_duba = pic_hash[:picture_duba]
picture_rsing = pic_hash[:picture_rsing]

sel.TypeText("360杀毒");
sel.TypeParagraph;
#argvs:$file;msoFalse # link to file ; msoTrue # save with document ;$left, $top, $width, $height
#ad.Shapes.AddPicture(picture_360.to_s,false,true,left,top,width,height)
sel.InlineShapes.AddPicture(picture_360.to_s,false,true,nil)

sel.TypeParagraph;
sel.TypeText("MCaffee杀毒");
sel.TypeParagraph;
sel.InlineShapes.AddPicture(picture_macaffee.to_s,false,true,nil)

sel.TypeParagraph;
sel.TypeText("Trend Pc-cilin杀毒");
sel.TypeParagraph;
sel.InlineShapes.AddPicture(picture_trend.to_s,false,true,nil)

sel.TypeParagraph;
sel.TypeText("金山毒霸杀毒");
sel.TypeParagraph;
sel.InlineShapes.AddPicture(picture_duba.to_s,false,true,nil)

sel.TypeParagraph;
sel.TypeText("瑞星杀毒");
sel.TypeParagraph;
sel.InlineShapes.AddPicture(picture_rsing.to_s,false,true,nil)

# word.ActiveDocument.Save
word.DefaultSaveFormat
d.saveas(report_filename);
# word.ActiveDocument.Close
# word.Documents.close()
word.quit()

end


pic_hash = {}
pic_hash[:picture_360] = pic_root+"/360_2012_03_31__20_54_27.bmp"
pic_hash[:picture_macaffee] = pic_root+"/macaffee_2012_04_01__21_18_36.bmp"
pic_hash[:picture_trend] = pic_root+"/trend_pccilin_2012_03_31__20_53_20.bmp"
pic_hash[:picture_duba] = pic_root+"/kingsoft_duba_2012_03_31__20_55_37.bmp"
pic_hash[:picture_rsing] = pic_root+"/rsing_2012_03_31__20_53_58.bmp"

word_report(filename,pic_hash,"att test")

 
| 0个评论