m.beginner
m.beginner

Reputation: 409

How to use Axlsx:NumFmt?

How do use Alxsx:NumFmt class?

I need to use this class to format currency values (positive and negative values)

I found some documentation for this class here - https://www.rubydoc.info/github/randym/axlsx/Axlsx/NumFmt

But there are no code samples available. Please help me on how to use this class.

Current Code:

currency_format_code = '$#,##0_;[Red]($#,##0_)' 
@default_style = wb.styles.add_style(:format_code => currency_format_code, 
  :sz => 10, :font_name => "Arial", 
  :alignment => {:horizontal => :right})
@italics_style = wb.styles.add_style(:format_code => currency_format_code, 
  :sz => 10, :font_name => "Arial Narrow", :i => true, 
  :alignment => {:horizontal => :right})

row_style = [nil, nil, nil, @default_left_style] + ([@default_style] * 25)

sheet.add_row[nil, nil, nil, day1, day2, day3, 
              day4, day5, day6, day7, day8, day9, 
              day10, day11, day12, day13, day14, 
              day15, day16, day17, day18, day19, 
              day20, day21, day22, day23, day24, 
              day25], :style => row_style

Upvotes: 1

Views: 747

Answers (2)

Christopher Oezbek
Christopher Oezbek

Reputation: 26353

Late to the party: To use the NumFmt numbers you add them to your style not using format_code, but the num_fmt option:

  number_style = p.workbook.styles.add_style({
    num_fmt: 2,
    alignment: { horizontal: :center, :vertical => :center},
    border: { color: "000000", style: :thin},
    bg_color: "F2F2F2"
  })

Upvotes: 0

engineersmnky
engineersmnky

Reputation: 29328

I am not sure you can make this more performant than what you already have. This issue is that the style is applied to each cell in the row individually array_to_cells

Excerpt:

def array_to_cells(values, options={})
  DataTypeValidator.validate :array_to_cells, Array, values
  types, style, formula_values = options.delete(:types), options.delete(:style), options.delete(:formula_values)
  values.each_with_index do |value, index|
    options[:style] = style.is_a?(Array) ? style[index] : style if style
    options[:type] = types.is_a?(Array) ? types[index] : types if types
    options[:formula_value] = formula_values[index] if formula_values.is_a?(Array)

    self[index] = Cell.new(self, value, options)
  end
end

So as you can see it loops through all 28 cells in the row and looks up the style that should be applied for each then creates a new Cell with that style. Which is probably where the degradation is coming from.

Upvotes: 1

Related Questions