【问题标题】:Edit docx using nokogiri and rubyzip使用 nokogiri 和 ruby​​zip 编辑 docx
【发布时间】:2012-02-22 21:27:11
【问题描述】:

在这里,我使用 ruby​​zip 和 nokogiri 来修改 .docx 文件。

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

当我在下面编写示例代码时,代码修改了文件,但其他文件受到干扰。换句话说,更新的文件没有打开显示错误,字处理器崩溃。我该如何解决这个问题?

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

【问题讨论】:

    标签: ruby zip nokogiri replace document-management


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      根据official Github documentation,你应该Use write_buffer instead open。链接中还有一个代码示例。

      【讨论】:

      • 他们关于 docx 的段落有点混乱。我知道DOCUMENT_FILE_PATHnew_path 指的是原始和新的docx 文件路径,但RELS_FILE_PATH 是什么?
      • 我的猜测是DOCUMENT_FILE_PATH 是单词文档xml 本身word/document.xmlRELS_FILE_PATHword/_rels/document.xml.rels。然而,在我将File.open(new_path, "w") {|f| f.write(buffer.string) } 更改为File.open(new_path, "wb") {|f| f.write(buffer.string) } 之前,github 文档上的示例对我不起作用(生成损坏的 .docx 文件),请注意二进制模式。
      猜你喜欢
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多