![1df053985acde9923842940db4dcd6b1.png](https://i-blog.csdnimg.cn/blog_migrate/4fd5eeed928c9e6789c27c15c75c425c.jpeg)
Hey,最近有很多粉丝私信询问,2020年已过半,又该统计半年报表信息了。
你关心的是,Ruby能否像VBA、Python一样,
实现多表格快速汇总?
答案是肯定的。
![d1c43f44c6ad947ebe550fc90d74bbf1.png](https://i-blog.csdnimg.cn/blog_migrate/7748f40a49a2098b674c656b6c658e9f.jpeg)
这期,为你讲解如何将多个Word表格汇总到Excel里。为了方便演示,我只模拟了3个Word数据文件。
![9b1bf9021261e2ac2592ff2ee6eb3268.png](https://i-blog.csdnimg.cn/blog_migrate/f71addcb24b8290d97e421ec38851cd6.jpeg)
![0f4ba84fc4d7f166ae4e2d360efb9ce8.png](https://i-blog.csdnimg.cn/blog_migrate/eff3dc53587b22827a8cbcc72a1fcf8e.jpeg)
001 需求分析
![cc25fc93371386121c1ba7c0d38b6438.png](https://i-blog.csdnimg.cn/blog_migrate/3a14ea361914054a89c806dc0622ebbb.jpeg)
表格里有培训名称、培训时间、主办方、培训地点、培训内容等项目。
Word表和Excel大致存储原理大致相同,他们都是由一个个cell组成的,但不同的是,在Excel里单元格对象是cells,而在Word里它则变成了cell。
002 思路解析
![036481aa087a54c76de7077477d76cf6.png](https://i-blog.csdnimg.cn/blog_migrate/9b5450aa7f6a97f1901da3579843d9af.png)
解题思路:
第一步,通过Ruby调用Office接口,打开Word、Excel。
第二步,将Word表的指定位置数据写入数组保存。第三步,将数组数据一次性写入Excel保存。第四步,检查是否存在问题,关闭相关文件。
003 代码展示
# 初始化
require "win32ole"
Pth=File.dirname(__FILE__)
Eap=WIN32OLE::new("Excel.Application")
Wap=WIN32OLE::new("word.Application");Wap.visible=true
arr=Array.new(100){[nil]}
filename=Dir.glob(Pth+'/*.doc')
s=0
# 提取文件
filename.each{|n|
wdc=Wap.documents.open(n)
t=wdc.tables.count
(1..t).each{|i|
# 培训名称
arr[s][0]=wdc.tables(i).cell(1,2).range.text.chop
# 培训时间
arr[s][1]=wdc.tables(i).cell(1,4).range.text.chop
# 主持人
arr[s][2]=wdc.tables(i).cell(2,2).range.text.chop
# 培训地点
arr[s][3]=wdc.tables(i).cell(2,4).range.text.chop
# 培训内容
arr[s][4]=wdc.tables(i).cell(3,2).range.text.chop
s+=1
}
# wdc.close
}
# 数据写入
ebk=Eap.workbooks.open(Pth+'/汇总.xls')
Eap.visible=true
ebk.worksheets(1).range("a2").resize(s,5).value=arr