Denys Medynskyi
Denys Medynskyi

Reputation: 2353

Can't export table into Excel

I was watching http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicast about exporting tables and follow all steps.

I have in my aplication.rb:

 require 'csv'

Added MimeType in mime_types.rb:

          Mime::Type.register "application/xls", :xls

My controller:

def index

if params[:report] && params[:report][:start_date] && params[:report][:end_date]
 start_date = params[:report][:start_date]
 end_date = params[:report][:end_date]
 @financial_reports = current_user.financial_reports.where(:created_at => start_date.to_date..end_date.to_date)

 respond_to do |format|
  format.html # index.html.erb
  format.csv { send_data @financial_reports.to_csv }
  format.xls
  format.json { render json: @financial_reports }
 end
end

end

In my model:

def self.to_csv(options = {})
  CSV.generate(options) do |csv|
  csv << column_names
  all.each do |product|
    csv << product.attributes.values_at(*column_names)
  end
end

end

and finally - links in view:

<%if @financial_reports%>  
 Download:
 <%= link_to "CSV", financial_reports_path(format: "csv") %> |
<%= link_to "Excel", financial_reports_path(format: "xls") %>
 ...
 <%end%>

when I'm clicking on Excel link giving me error:

         undefined method `each' for nil:NilClass

but I DO see data in table(html)!

Also, when I'm clicking CSV:

    Template is missing

I restarted my application when added something in configuration files.

Can someone help me ?

Upvotes: 0

Views: 1297

Answers (1)

pdpMathi
pdpMathi

Reputation: 775

There are few mistakes in your code

@financial_reports = current_user.financial_reports.where(:created_at => start_date.to_date..end_date.to_date)

you are filtering the financial reports based on start date and end date. It will return you a collection of financial_reports. So you can not directly call @financial_reports.to_csv. Another way you can send it as a parameter of a method like

 format.csv { send_data FinancialReport.to_csv(@financial_reports) }

and in the model

def self.to_csv(reports,options = {})
  CSV.generate(options) do |csv|
  csv << column_names
  reports.each do |product|
    csv << product.attributes.values_at(*column_names)
  end
end

Template is missing - error will happen when you dont have a corresponding view file

Check whether you have the /app/views/products/index.xls.erb file as specified in your reference http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicast

Upvotes: 3

Related Questions