Skip to content

Instantly share code, notes, and snippets.

@mumriks mumriks/odsgrep.rb
Last active Aug 29, 2015

Embed
What would you like to do?
Libre Office の集計表ファイル(.ods)を行単位で検索。(家計簿ファイルを想定)要:RubyZip
# encoding: utf-8
#
require 'rexml/document'
require 'rubygems'
require 'zip/filesystem'
def usage
print "usage: ruby odsgrep.rb <検索文字列> files...\n"
exit(1)
end
usage if ARGV.size < 2
pat = Regexp.new(ARGV.shift.encode("UTF-8"))
ARGV.each {|ods|
ods = File.expand_path(ods).gsub(/\//s, "\\")
puts "file:#{ods}"
Zip::File.open(ods) {|zip|
doc = REXML::Document.new(zip.file.read("content.xml"))
sheets = doc.elements["/office:document-content/office:body/office:spreadsheet"]
sheets.each_element {|sheet|
sheetname = sheet.attributes['name']
rownum = 0
sheet.each_element {|table|
rownum += 1 if table.expanded_name == 'table:table-row'
rownum += table.attributes['number-rows-repeated'].to_i - 1 if table.attributes['number-rows-repeated']
text = ""
table.each_element {|row|
row.each_element {|cell|
text = text + "\t" + cell.text
}
}
if text =~ pat
puts "sheet:#{sheetname} row:#{rownum}"
puts text
end
}
}
}
puts
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.