8

rubyzip と nokogiri を組み合わせて .docx ファイルを編集しています。rubyzip を使用して .docx ファイルを解凍し、nokogiri を使用して word/document.xml ファイルの本文を解析および変更していますが、最後に ruby​​zip を閉じるたびにファイルが破損し、開くことができません。修理してください。デスクトップで .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
4

3 に答える 3

12

昨夜、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
于 2011-01-12T14:27:57.107 に答える
1

ルビーやノコギリについては何も知らなかったのですが...

新しいコンテンツを正しく再圧縮していないようです。rubyzip についてはわかりませんが、エントリ word/document.xml を更新してからファイルを再保存/再圧縮するように指示する方法が必要です。

エントリを新しいデータで上書きしているように見えますが、もちろんサイズが異なり、残りのzipファイルが完全に台無しになります。

この投稿でExcelの例を示しますテキストファイルを解析してExcelレポートを作成します

別のzipライブラリとVBを使用している場合でも、これは役立つ可能性があります(私はまだあなたがやろうとしていることを正確に行っています.私のコードは約半分です)

ここに該当する部分があります

Using z As ZipFile = ZipFile.Read(xlStream.BaseStream) 
'Grab Sheet 1 out of the file parts and read it into a string. 
Dim myEntry As ZipEntry = z("xl/worksheets/sheet1.xml") 
Dim msSheet1 As New MemoryStream 
myEntry.Extract(msSheet1) 
msSheet1.Position = 0 
Dim sr As New StreamReader(msSheet1) 
Dim strXMLData As String = sr.ReadToEnd 

'Grab the data in the empty sheet and swap out the data that I want  
Dim str2 As XElement = CreateSheetData(tbl) 
Dim strReplace As String = strXMLData.Replace("<sheetData/>", str2.ToString) 
z.UpdateEntry("xl/worksheets/sheet1.xml", strReplace) 
'This just rezips the file with the new data it doesnt save to disk 
z.Save(fiRet.FullName) 
End Using 
于 2010-11-08T16:37:23.913 に答える
1

公式の Github ドキュメントによると、次のようにする必要がありUse write_buffer instead openます。リンク先にコード例もあります。

于 2014-02-01T02:22:11.917 に答える