简体   繁体   English

使用nokogiri和rubyzip编辑docx

[英]Edit docx using nokogiri and rubyzip

Here, I'm using a rubyzip and nokogiri to modify a .docx file. 在这里,我使用rubyzip和nokogiri来修改.docx文件。

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

According to the official Github documentation , you should Use write_buffer instead open . 根据官方Github文档 ,您应该Use write_buffer instead open There's also a code example at the link. 链接上还有一个代码示例。

Following is the code that edit the content of a .docx template file.It first creae a new copy of your template.docx remember u will create this template file and keep this file in the same folder where you create your ruby class like you will create My_Class.rb and copy following code in it.It works perfectly for my case. 以下是编辑.docx模板文件内容的代码。首先创建一个新的template.docx副本。记住你将创建这个模板文件并将此文件保存在你创建ruby类的同一个文件夹中创建My_Class.rb并在其中复制以下代码。它完全适合我的情况。 Remember you need to install rubyzip and nokogiri gem in a gemset.(Google them to install).Thanks 请记住,你需要在gemset中安装rubyzip和nokogiri gem。(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM