I am able to export table data to a CSV file, however there is a blank row after every record. Why and how do i fix it?
in index.html.erb
<%= link_to "Export to csv", request.parameters.merge({:format => :csv})%>
in index.csv.erb
<%- headers = ["Id", "Name"] -%>
<%= CSV.generate_line headers %>
<%- @customers.each do |n| -%>
<%- row = [ n.id, n.fname ] -%>
<%= CSV.generate_line row %>
<%- end -%>
CSV.generate_line
adds a new line character to the end of the line it generates, but so does <%= %>
so you're getting two new lines.
To suppress the new line character from the erb
expression output use this syntax: <%= -%>
so:
<%- headers = ["Id", "Name"] -%>
<%= CSV.generate_line headers -%>
<%- @customers.each do |n| -%>
<%- row = [ n.id, n.fname ] -%>
<%= CSV.generate_line row -%>
<%- end -%>
The accepted answer leaves in the new line generated from the erb
but suppresses the new line from CSV.generate_line
which I think is not the best way to do it.
This is what fixed it.
<%= CSV.generate_line row, :row_sep => ?\t, :quote_char => ?\ %>
for me following use of strip and html_safe worked, applied after the row was generated:
<%- headers = ["Id", "Tour No"] -%>
<%= CSV.generate_line(headers).strip%>
<%- @tours.each do |t| -%>
<%- row = [ t.id,t.tour_no] -%>
<%= CSV.generate_line(row).html_safe.strip%>
<%- end -%>
Try this:
row = [ n.id, n.fname.strip ]
strip will remove \r and/or \n which might cause the blank lines. I dont have any other explaination your sourcecode is okay!
I thought I would chip in with my solution as just been struggling with this.
Basically on my local machine (a mac) everything was working absolutely fine, then when I deployed my app to heroku it would start adding in these mystery new rows.
For me the solution was to use:
CSV.generate_line(row, row_step: ?\r).html_safe
As a note, I'm using rails 4.1.6.
Hope that helps some other people struggling