Module: TSV::XLS

Defined in:
lib/rbbt/tsv/excel.rb

Class Method Summary collapse

Class Method Details

.read(file, options = {}) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/rbbt/tsv/excel.rb', line 96

def self.read(file, options = {})
  options = Misc.add_defaults options, :sep2 => /[,|]\s?/
  sheet = Misc.process_options options, :sheet
  header = Misc.process_options options, :header

  header = true unless header == false
  sheet ||= 0
  TmpFile.with_file do |filename|
    workbook = Spreadsheet.open Open.open(file)
    sheet    = workbook.worksheet sheet

    rows = []

    sheet.each do |row|
      rows << row.values_at(0..(row.size - 1)).collect{|c| String === c ? c.gsub("\n", ' ') : c }
    end

    File.open(filename, 'w') do |f|
      if header
        header = rows.shift
        f.puts "#" + header * "\t"
      end

      rows.each do |row| 
        values =  row.collect{|c| c.respond_to?(:value) ? c.value : c }
        f.puts values * "\t"
      end
    end

    TSV.open(filename, options)
  end
end

.write(tsv, file, options = {}) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/rbbt/tsv/excel.rb', line 129

def self.write(tsv, file, options = {})
  options = Misc.add_defaults options, :sheet => "Sheet1"
  sheet = Misc.process_options options, :sheet
  fields, rows = TSV._excel_data(tsv, options)

  book = Spreadsheet::Workbook.new
  sheet1 = book.create_worksheet 
  sheet1.name = sheet if sheet

  sheet1.row(0).concat fields

  rows.each_with_index do |cells,i|
    sheet1.row(i+1).concat cells
  end

  book.write file
end