首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用nokogiri和rubyzip编辑docx

使用nokogiri和rubyzip编辑docx
EN

Stack Overflow用户
提问于 2012-01-31 13:23:58
回答 2查看 2.1K关注 0票数 5

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

代码语言:javascript
复制
RubyZip -> Unzip .docx file
Nokogiri -> Parse and change in content of the body of word/document.xml

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

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2014-02-01 10:24:59

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

票数 2
EN

Stack Overflow用户

发布于 2013-02-09 18:58:38

以下是编辑.docx模板内容的代码,首先创建一个新的template.docx副本,记住,您将创建这个模板文件,并将此文件保存在创建ruby类的同一文件夹中,就像您将创建My_Class.rb一样,并在it.It中复制以下代码,非常适合我的情况。记住你需要在一个gemset中安装rubyzip和nokogiri gem。(谷歌他们安装).Thanks

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9074828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档