ruby中的word2007文件修改操作
2010-05-10, Posted in Ruby, 软件开发 | 3 回复
使用ruby修改word2007,到目前并没有好的库,当然,rails也一样,那么如何才能用ruby操作word2007文件呢?word2007文件,也就是docx文件,实际就是一个zip压缩的压缩包,它里面由一系列xml及其它与文件内容相关的资源文件组成,所以,最简单的办法就是解压这个docx文件,然后修改xml文件,再把他打包,完成修改。首先表一下本人的开发环境:
ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin9]
gem 1.3.6
zipruby (0.3.6)
nokogiri (1.4.1)
libxml-ruby (1.1.3)
Rails 2.3.4(这个非必须,本人是在rails下开发的)
刚才说了,修改的思路分为三步:
第一步:解压docx文件。
第二步:查找并修改document.xml文件中的内容
第三步:重新生成docx文件
根据以上三步,model代码对应如下:
#office_open_xml.rb require 'zipruby' require 'nokogiri' class OfficeOpenXml def initialize(template,newdoc) #Store the instance variables @template, @newdoc = template, newdoc end def parse() existing_xml = get_xml_from_template() body_node = existing_xml.root.xpath("w:body", {"w" => "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}).first #修改文件操作 body_node.xpath("//w:r//w:t").each do |child| child.content = child.content.gsub("{name}", "replace string") end compress(existing_xml) end #解压文件 def get_xml_from_template() filename = 'word/document.xml'; #retrieve the document from the template doc xml = Zip::Archive.open(@template) do |zipfile| zipfile.fopen(filename).read end #parse the resulting file into the Nokogiri xml doc Nokogiri::XML.parse(xml) end #把修改过的文件重新生成docx def compress(newXML) #Copy the template to the new document FileUtils.copy(@template, @newdoc) #Open the zip archive Zip::Archive.open(@newdoc, Zip::CREATE) do |zipfile| #Replace the document.xml with our new xml zipfile.add_or_replace_buffer('word/document.xml', newXML.to_s) end end end
Controller的代码对应如下:
#office_controller.rb class OfficeController < ApplicationController def index office = OfficeOpenXml.new("#{RAILS_ROOT}/public/template/test.docx","#{RAILS_ROOT}/public/template/test333.docx") render :text => office.parse() end end
如果有兴趣,大家也可以参看这篇文章:
Using Ruby on Rails and XSLT to Create a Word 2007 Document
May 11th, 2010 on 17:54:13
哈哈,内容经典,拜读了,小站来过了,有空博主记得回访哦。
May 11th, 2010 on 18:23:33
哥回来了,过来看看。
May 12th, 2010 on 09:08:32
跑哪去发财了呢?