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.
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With