Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a CSV file into an HTML table using Ruby?

I am trying to read a simple CSV file into an HTML table to be displayed in a browser, but I'm running into trouble. This is what I'm trying:

Controller:

def show
  @csv = CSV.open("file.csv", :headers => true)
end

View:

<% @csv.read %>
<% @csv.headers.each do |head| %>
<%= head %>
<% end %>

<table border="1">
  <% @csv.each do |row| %>
  <tr>
    <% row.each do |element| %>
      <td> <%= element %> </td>
    <% end %>
  </tr>
  <% end %>
</table>

Output:

Name Start Date End Date Quantity Postal Code

Basically I am only getting the header, and the CSV body isn't being read and rendered.

like image 535
Anthony To Avatar asked Aug 08 '13 16:08

Anthony To


1 Answers

This ended up being the final solution:

Controller:

  def show
    # Open a CSV file, and then read it into a CSV::Table object for data manipulation
    @csv_table = CSV.open("file.csv", :headers => true).read
  end

View:

<table border="0" cellspacing="5" cellpadding="5">
  <tr>
  <% @csv_table.headers.each do |header| %>
    <th><%= header %></th>
  <% end %> 
  </tr>
  <% @csv_table.each do |row| %>
    <tr>
    <% row.each do |element| %>
      <td><%= element[1] %></td>
    <% end %>
    </tr>
  <% end %> 
</table>

Reading the CSV into a table was the correct way to go about it, but when iterating through the rows, I had to specify element[1], since element is actually an array of [header, element].

like image 59
Anthony To Avatar answered Sep 28 '22 08:09

Anthony To