ruby axlsx gem:在不使用add-row的情况下为axlsx工作表分配公式

时间:2017-06-14 14:00:14

标签: ruby-on-rails ruby axlsx

根据官方示例,可以在add_row https://github.com/randym/axlsx/blob/master/examples/example.rb#L355期间为工作表分配公式

我的问题是,当表格填满时,是否可以为列分配公式?

1 个答案:

答案 0 :(得分:0)

以下是将公式添加到现有单元格的示例。

pk = Axlsx::Package.new
wb = pk.workbook
sheet = wb.add_worksheet(name: 'Test')
sheet.add_row(['First', 'Second', 'Third'])
sheet.add_row([1, 1, 1])
sheet.add_row([2, 2, 2])
sheet.add_row([3, 3, 0])    # we will be updating the last cell in this row (C4)
sheet.add_row([4, 4, 4])

cell = sheet['C4']
cell.type = :string         # it is important to ensure the type of the cell is set before adding the formula
cell.value = '=A3+A4'

pk.serialize("example.xlsx")

以下是动态更新单元格公式的示例:

pk = Axlsx::Package.new
wb = pk.workbook
sheet = wb.add_worksheet(name: 'Test')
sheet.add_row(['First', 'Second', 'Third'])
sheet.add_row([1, 1, 1])
sheet.add_row([2, 2, 2])
sheet.add_row([3, 3, 3])
sheet.add_row([4, 4, 4])

cells = sheet["C2:C5"]  # select an array of cells

cells.each do |cell|
  row_index = cell.row.index + 1
  cell.type = :string
  cell.value = "=SUM(A#{row_index}:B#{row_index})"
end

pk.serialize("example2.xlsx")