ruby-on-rails – 如何使用nokogiri和rubyzip编辑docx
发布时间:2020-12-16 19:16:14 所属栏目:百科 来源:网络整理
导读:我正在使用 rubyzip和nokogiri的组合来编辑.docx文件.我正在使用rubyzip来解压缩.docx文件,然后使用nokogiri来解析和更改word / document.xml文件的主体但是有时候我最后关闭rubyzip它会破坏文件而我无法打开它或者修理它.我在桌面上解压缩.docx文件并检查wo
我正在使用
rubyzip和nokogiri的组合来编辑.docx文件.我正在使用rubyzip来解压缩.docx文件,然后使用nokogiri来解析和更改word / document.xml文件的主体但是有时候我最后关闭rubyzip它会破坏文件而我无法打开它或者修理它.我在桌面上解压缩.docx文件并检查word / document.xml文件,并将内容更新为我更改为的内容,但所有其他文件都搞砸了.有人可以帮我解决这个问题吗?这是我的代码:
require 'rubygems' require 'zip/zip' require 'nokogiri' zip = Zip::ZipFile.open("test.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 = "New Text" zip.get_output_stream("word/document.xml") {|f| f << xml.to_s} zip.close 解决方法
昨晚我遇到了与rubyzip相同的腐败问题.我通过将所有内容复制到新的zip文件来解决它,根据需要替换文件.
这是我的工作概念证明: #!/usr/bin/env ruby require 'rubygems' require 'zip/zip' # rubyzip gem require 'nokogiri' class WordXmlFile def self.open(path,&block) self.new(path,&block) end def initialize(path,&block) @replace = {} if block_given? @zip = Zip::ZipFile.open(path) yield(self) @zip.close else @zip = Zip::ZipFile.open(path) end end def merge(rec) xml = @zip.read("word/document.xml") doc = Nokogiri::XML(xml) {|x| x.noent} (doc/"//w:fldSimple").each do |field| if field.attributes['instr'].value =~ /MERGEFIELD (S+)/ text_node = (field/".//w:t").first if text_node text_node.inner_html = rec[$1].to_s else puts "No text node for #{$1}" end end end @replace["word/document.xml"] = doc.serialize :save_with => 0 end def save(path) Zip::ZipFile.open(path,Zip::ZipFile::CREATE) do |out| @zip.each do |entry| out.get_output_stream(entry.name) do |o| if @replace[entry.name] o.write(@replace[entry.name]) else o.write(@zip.read(entry.name)) end end end end @zip.close end end if __FILE__ == $0 file = ARGV[0] out_file = ARGV[1] || file.sub(/.docx/,' Merged.docx') w = WordXmlFile.open(file) w.force_settings w.merge('First_Name' => 'Eric','Last_Name' => 'Mason') w.save(out_file) end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |