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

環境

  • 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」を使用して、読み込む「シート」を指定します。

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

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

これでシートを指定して、読み込むことが可能です。

サンプル

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

「ExcelImportController」というController内でシートを指定します。

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」という名前で作成してます。
以下のように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 にアクセスすると
指定されたシートのデータが表示されていることが確認できます。