RubyZip 解压缩 .docx、修改和压缩备份会引发 Errno::EACCESS 错误

RubyZip Unzipping .docx, modifying, and zipping back up throws Errno::EACCESS error

所以,我使用 Nokogiri 和 Rubyzip 解压一个 .docx 文件,修改其中的 word/docoument.xml 文件(在这种情况下,只需将包含的每个元素更改为 "Dreams!"), 然后把它压缩回来。

require 'nokogiri'
require 'zip'

zip = Zip::File.open("apple.docx")
doc = zip.find_entry("word/document.xml")

xml = Nokogiri::XML.parse(doc.get_input_stream)

inputs = xml.root.xpath("//w:t")

inputs.each{|element| element.content = "DREAMS!"}

zip.get_output_stream("word/document.xml", "w") {|f| f.write(xml.to_s)}

zip.close

运行 通过 IRB 的代码逐行运行完美,并根据需要对 .docx 文件进行更改,但是如果我 运行 来自命令行的脚本

ruby xmltodoc.rb   

我收到以下错误:

C:/Ruby193/lib/ruby/gems/1.9.1/gems/rubyzip-1.1.7/lib/zip/file.rb:416:in `rename': Permission denied - (C:/Users/Bane/De
sktop/apple.docx20150326-6016-k9ff1n, apple.docx) (Errno::EACCES)
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rubyzip-1.1.7/lib/zip/file.rb:416:in `on_success_replace'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rubyzip-1.1.7/lib/zip/file.rb:308:in `commit'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rubyzip-1.1.7/lib/zip/file.rb:332:in `close'
        from ./xmltodoc.rb:15:in `<main>' 

我计算机上的所有用户都拥有该 .docx 文件的所有权限。该文件也没有任何特殊设置——只是一个带有段落的新文件。此错误仅出现在 Windows 上,但脚本在 Mac 和 Ubuntu 上运行完美。 运行 Powershell 作为管理员抛出同样的错误。有什么想法吗?

在我的 Windows 7 系统上,以下工作。

require 'nokogiri'
require 'zip'

Zip::File.open("#{File.dirname(__FILE__)}/apple.docx") do |zipfile|
  doc = zipfile.read("word/document.xml")
  xml = Nokogiri::XML.parse(doc)
  inputs = xml.root.xpath("//w:t")
  inputs.each{|element| element.content = "DREAMS!"}
  zipfile.get_output_stream("word/document.xml") {|f| f.write(xml.to_s)}
end

您也可以使用 gem docx,这是一个示例,书签的名称是荷兰语,因为这是我的 MS Office 使用的语言。

require 'docx'

# Create a Docx::Document object for our existing docx file
doc = Docx::Document.open('C:\Users\Gebruiker\test.docx'.gsub(/\/,'/'))

# Insert a single line of text after one of our bookmarks
# p doc.bookmarks['bladwijzer1'].methods
doc.bookmarks['bladwijzer1'].insert_text_after("Hello world.")

# Insert multiple lines of text at our bookmark
doc.bookmarks['bladwijzer3'].insert_multiple_lines(['Hello', 'World', 'foo'])

# Save document to specified path
doc.save('example-edited.docx')