rails6 EXCEL最終行まで読み込む

rails6 EXCEL最終行まで読み込む

rails6でEXCEL最終行まで読み込むまでの手順を記述してます。Railsのバージョンは6.1.3を使用してます。

環境

  • OS CentOS Linux release 7.9.2009 (Core)
  • Ruby 3.0.0
  • Rails 6.1.3

rooインストール

ここでは、excelファイルを読み込むために、「roo」を使用してます。

インストールは、まずGemfileに以下を追加します。

gem "roo"

インストールします。

bundle install

最終行まで読み込む

ライブラリ「roo」を使用して、最終行まで読み込む場合は「sheet」を指定してから「last_row」で取得することができます。

@excel = Roo::Excelx.new("./hoge.xlsx")

@sheet = @excel.sheet("読み込むシート名")

logger.debug(@sheet.last_row)

これで最終行まで読み込むことが可能です。

最終列は、以下で取得可能です。

@sheet.last_column

サンプル

実際に、シートを指定してEXCELを読み込んでみます。
読み込むEXCELファイルは「Book1.xlsx」という名称で、データは下図となります。

「ExcelImportController」というController内でシートを指定します。
※ここでは「foo」シートのデータの最終行まで取得します。

class ExcelImportController < ApplicationController
  
  @@excel_test = Roo::Excelx.new("./Book1.xlsx")

  def test
    @excel = @@excel_test
    @sheet = @excel.sheet("foo")
  end
end

view側のファイル名は「test.html.erb」として、
以下のように「.each_row_streaming(offset: 0, max_rows: @sheet.last_row)」で最終行まで繰り返しを行います。
※デザインにはbootstrapを使用してます。

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header card-header-primary">
              <h4 class="card-title ">excel result</h4>            
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table">
                      <thead class=" text-primary">
                          <th>
                          1列目
                          </th>
                          <th>
                          2列目
                          </th>
                          <th>
                          3列目
                          </th>
                          <th>
                          4列目
                          </th>
                          <th>
                          5列目
                          </th>                         
                      </thead>
                      <tbody>

                        <% @excel.each_row_streaming(offset: 0, max_rows: @sheet.last_row) do |excels| %>
                          <tr>
                          <% excels.each do |a| %>
                            <td><%= a.value %></td>
                          <% end %>
                          </tr>
                        <% end %>

                      </tbody>
                    </table>
                </div>      
              </div>
          </div>
      </div>
</div>

「routes.rb」には、以下を追加してます。

get "exceltest", to: "excel_import#test"

これで。「rails s」で起動して、ブラウザから http://プライベートIP or サーバーアドレス:3000/exceltest にアクセスすると指定されたシートのデータが表示されていることが確認できます。