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テンプレートファイルのコンテンツを編集するコードです。最初に、template.docxの新しいコピーを作成します。このテンプレートファイルを作成し、このファイルを、rubyクラスを作成するのと同じフォルダーに保持することを忘れないでください。 My_Class.rbを作成し、その中に次のコードをコピーします。私の場合は完全に機能します。rubyzipとnokogirigemをgemsetにインストールする必要があることを忘れないでください(Googleでインストールしてください)。ありがとう

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 に答える