LoginSignup
1
1

More than 3 years have passed since last update.

RubyXLで最初のシート(テンプレート)から複数のシートを作成する2

Last updated at Posted at 2021-03-16

以前書いた記事の続報です。前回の記事だけでは解決できない2つの不具合に遭遇しましたので情報を共有します。
https://qiita.com/DYO/items/bbdac8a9521cdaf5757e

  • 計算式がコピーされない
  • 計算が反映されない

こちらは前回までコードの一部でテンプレートのセルを新しいセルにコピーするメソッドです。

  def cell_render(template_cell, row_num, col_num)
    cell = @worksheet.add_cell(row_num, col_num, content_eval(template_cell.value))
    cell.style_index = template_cell.style_index
  end

テンプレートのセルが計算式の場合は template_cell.value の中身は''かnilになるので計算式はコピーされませんでした。

そこで以下のようにしました。

  def cell_render(template_cell, row_num, col_num)
    cell =
      if template_cell.formula.nil?
        content = content_eval(template_cell)
        @worksheet.add_cell(row_num, col_num, content)
      else
        expression = template_cell.formula.expression
        cell = @worksheet.add_cell(row_num, col_num, '', expression)
        cell.formula = template_cell.formula.dup
        cell.formula.ca = true
        cell
      end
    cell.style_index = template_cell.style_index
  end

template_cell.formula.nil? でそのセルが計算式かどうかがわかります。
template_cell.formula.expression で計算式が取得できます。

しかし、計算式が入っているにもかかわらず template_cell.formula.expression が空になってしまうケースがありました。

その理由はテンプレートとなるエクセルを編集するときに、計算式をコピーしたり、フィルハンドルをドラッグして一気に入力させたりするとエクセルの内部データとしては template_cell.formula.expression は空のままで、元のセルを参照する形になるからです。

そこで一旦追加したセルにテンプレートのformulaをコピーして代入することで参照情報も追加します。
cell.formula = template_cell.formula.dup
これで一つ目の問題は解決しました。

もう一つ問題だったのがセルに計算式は入っているけれども見た目が空になることがありました。つまり計算が行われていない状態でファイルが開くという現象です。一度そのテキストを選択して確定すると計算されるような感じでした。調べてみるとformulaには「計算しろ」というフラグがあって、それをtrueにすることで解決できました。 cell.formula.ca = true

formulaのプロパティはこちらのドキュメントで確認できます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1