rails 3.1 generating CSV file

こ雲淡風輕ζ 提交于 2019-12-13 13:02:02

问题


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 -%>

回答1:


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.




回答2:


This is what fixed it.

<%= CSV.generate_line row, :row_sep => ?\t, :quote_char => ?\ %>



回答3:


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 -%>



回答4:


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!




回答5:


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



来源:https://stackoverflow.com/questions/7812231/rails-3-1-generating-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!