5

Here, I'm using a rubyzip and nokogiri to modify a .docx file.

RubyZip -> Unzip .docx file
Nokogiri -> Parse and change in content of the body of word/document.xml

As I wrote the sample code just below but code modify the file but others file were disturbed. In other words, updated file is not opening showing error the word processor is crashed. How can I resolve this issue ?

require 'zip/zipfilesystem'
require 'nokogiri'
zip = Zip::ZipFile.open("SecurityForms.docx")
doc = zip.find_entry("word/document.xml")
xml = Nokogiri::XML.parse(doc.get_input_stream)
wt = xml.root.xpath("//w:t", {"w" => "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}).first
wt.content = "FinalStatement"
zip.get_output_stream("word/document.xml") {|f| f << xml.to_s}
zip.close
4

2 回答 2

2

根据官方 Github 文档,您应该Use write_buffer instead open。链接中还有一个代码示例。

于 2014-02-01T02:24:58.753 回答
1

以下是编辑 .docx 模板文件内容的代码。它首先创建模板的新副本。请记住,您将创建此模板文件并将此文件保存在您创建 ruby​​ 类的同一文件夹中,就像您将创建 My_Class.rb 并在其中复制以下代码。它非常适合我的情况。请记住,您需要在 gemset 中安装 ruby​​zip 和 nokogiri gem。(谷歌安装)。谢谢

require 'rubygems'
require 'zip/zipfilesystem'
require 'nokogiri'
class Edit_docx
def initialize
coupling =  [('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten
secure_string  =  (0...50).map{ coupling[rand(coupling.length)] }.join
FileUtils.cp 'template.docx', "#{secure_string}.docx"
zip = Zip::ZipFile.open("#{secure_string}.docx")
doc = zip.find_entry("word/document.xml")
xml = Nokogiri::XML.parse(doc.get_input_stream)
wt = xml.root.xpath("//w:t", {"w"=>"http://schemas.openxmlformats.org/wordprocessingml/2006/main"})
#puts wt
wt.each_with_index do |tag,i|
tag.content = i.to_s + ""
end
zip.get_output_stream("word/document.xml") {|f| f << xml.to_s}
zip.close
puts secure_string
#FileUtils.rm("#{secure_string}.docx")
end
N.new
end
于 2013-02-09T10:58:38.467 回答