ruby-on-rails – 在Ruby中打开.doc文件

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在Ruby中打开.doc文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以打开一个.doc文件并使用 Ruby获取文件内容吗?

解决方法

宝石docx使用起来非常简单
  1. require 'docx'
  2.  
  3. puts Docx::Document.open('test.docx')

要么

  1. d = Docx::Document.open('test.docx')
  2. d.each_paragraph do |p|
  3. puts p
  4. end

您可以在https://github.com/chrahunt/docx找到它,并通过gem install docx进行安装

然而,docx不支持.doc文件(word 2007及更早版本),那么可以使用WIN32OLE:

  1. require 'win32ole'
  2.  
  3. begin
  4. word = WIN32OLE.connect('Word.Application')
  5. doc = word.ActiveDocument
  6. rescue
  7. word = WIN32OLE.new('word.application')
  8. path_open = 'C:\Users\...\test.doc' #yes: backslashes in windows
  9. doc = word.Documents.Open(path_open)
  10. end
  11.  
  12. word.visible = true
  13. doc.Sentences.each { |x| puts x.text }

猜你在找的Ruby相关文章