Note that there are some explanatory texts on larger screens.

plurals
  1. POExporting to CSV from complex rails query
    primarykey
    data
    text
    <p>I was following this <a href="http://railscasts.com/episodes/362-exporting-csv-and-excel" rel="nofollow noreferrer">railscast</a> video but I'm having serious difficulties to export my data to excel (or CSV for this matter).</p> <p>I'm using will_paginate in some data that I show on frontend like this:</p> <pre><code>sql = "select complex..." @data = paginate_by_sql([sql], :per_page =&gt; params[:rows], :page =&gt; params[:page]) </code></pre> <p>so, as is, I thought this should work:</p> <pre><code>respond_to do |format| format.html format.xls { send_data @data.to_csv(:col_sep =&gt; "\t") } end </code></pre> <p>and it actually downloaded a xls file correctly by the content is all messed up, it shows one row per column and something like this as content: </p> <p><code>#&lt;Product:0x00000004c83328&gt;</code></p> <p>PS -> using rails latest version</p> <p>:: EDIT :: By one row per column I mean one row only on my excel sheet and on this row</p> <p>COLUMN A = <code>#&lt;Product:0x00000004c83328&gt;</code></p> <p>COLUMN B = <code>#&lt;Product:0x00000004c83329&gt;</code></p> <p>COLUMN C = <code>#&lt;Product:0x00000004c8333&gt;</code> (30 columns)</p> <p><strong>UPDATE</strong></p> <p>Did a simple exercise for testing and end up with all columns again in one column only:</p> <pre><code>csv_string = CSV.generate(:col_sep =&gt; ",") do |csv| csv &lt;&lt; ["row", "of", "CSV", "data"] csv &lt;&lt; ["another", "row"] end respond_to do |format| format.html format.csv { send_data csv_string, :type =&gt; 'text/csv; charset=iso-8859-1; header=present', :disposition =&gt; "attachment; filename=records.csv" } end </code></pre> <p><code>(:col_sep =&gt; ",")</code> is optional I suppose.</p> <p>result: </p> <p><img src="https://i.stack.imgur.com/SjH14.png" alt="excel output"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload