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」というgemをインストールします。
Gemfileに以下を追加します。
1 |
gem "roo" |
インストールします。
1 |
bundle install |
EXCELファイル用意
下図の内容のEXCELファイルを「Book1.xlsx」という名前で作成してます。

controller作成
excelを読み込むための「excel_import」というcontrollerを作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
rails g controller excel_import <出力結果> Running via Spring preloader in process 44714 create app/controllers/excel_import_controller.rb invoke erb create app/views/excel_import invoke test_unit create test/controllers/excel_import_controller_test.rb invoke helper create app/helpers/excel_import_helper.rb invoke test_unit invoke assets invoke scss create app/assets/stylesheets/excel_import.scss |
controller内でEXCEL「Book1.xlsx」を読み込みます
1 2 3 4 5 6 |
class ExcelImportController < ApplicationController def index @excel = Roo::Excelx.new("/home/scorejp/postgres-docker/sssytem/Book1.xlsx") end end |
View作成
次に表示するためのviewを作成します。
「excel_import」配下に「index.html.erb」を作成します。

以下の内容で「index.html.erb」を編集します。
※見やすくするために「bootstrap」を使ってます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<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: 6) do |excels| %> <tr> <% excels.each do |a| %> <td><%= a.value %></td> <% end %> </tr> <% end %> </tbody> </table> </div> </div> </div> </div> </div> <br> |
route作成
最後にルーティングを設定します。
1 |
get "excel", to: "excel_import#index" |
EXCELファイル内容確認
railsを起動してブラウザから http://プライベートIP or サーバーアドレス/excel:3000 にアクセスします。
1 |
rails s |
表示結果

EXCELファイルの内容が表示されていることが確認できます。
-
前の記事
rails6 nginx + pumaを使用する 2021.03.24
-
次の記事
React.js ライブラリ「react-likert-scale」を使って リッカート尺度を実装する 2021.03.24
コメントを書く