Method: RubyXL::WorksheetConvenienceMethods#insert_column

Defined in:
lib/rubyXL/convenience_methods/worksheet.rb

#insert_column(column_index = 0) ⇒ Object

Inserts column at column_index, pushes everything right, takes styles from column to left NOTE: use of this method will break formulas which reference cells which are being “pushed right”



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/rubyXL/convenience_methods/worksheet.rb', line 160

def insert_column(column_index = 0)
  validate_workbook
  ensure_cell_exists(0, column_index)

  old_range = cols.get_range(column_index)

  # Go through each cell in column
  sheet_data.rows.each_with_index { |row, row_index|
    next if row.nil? # Do not process blank rows

    old_cell = row[column_index]
    c = nil

    if old_cell && old_cell.style_index != 0 &&
         old_range && old_range.style_index != old_cell.style_index then

      c = RubyXL::Cell.new(:style_index => old_cell.style_index, :worksheet => self,
                           :row => row_index, :column => column_index,
                           :datatype => RubyXL::DataType::SHARED_STRING)
    end

    row.insert_cell_shift_right(c, column_index)
  }

  cols.insert_column(column_index)

  # Update merged cells for all rows below
  if self.merged_cells then
    merged_cells.each { |mc|
      next if mc.ref.col_range.last < column_index

      in_merged_cell = mc.ref.row_range.first < column_index
      mc.ref = RubyXL::Reference.new(
        mc.ref.row_range.first,
        mc.ref.row_range.last,
        mc.ref.col_range.first + (in_merged_cell ? 0 : 1),
        mc.ref.col_range.last + 1,
      )
    }
  end

  # TODO: update column numbers
end