【问题标题】:Can't export table into Excel无法将表格导出到 Excel
【发布时间】:2012-08-09 07:08:22
【问题描述】:

我正在观看 http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicast 关于导出表格并遵循所有步骤。

我的 aplication.rb 中有:

 require 'csv'

在 mime_types.rb 中添加了 MimeType:

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

我的控制器:

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

结束

在我的模型中:

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

结束

最后 - 视图中的链接:

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

当我点击 Excel 链接时出现错误:

         undefined method `each' for nil:NilClass

但我确实在表 (html) 中看到了数据!

另外,当我点击 CSV 时:

    Template is missing

在配置文件中添加内容后,我重新启动了我的应用程序。

有人可以帮我吗?

【问题讨论】:

    标签: ruby-on-rails export-to-excel


    【解决方案1】:

    您的代码中几乎没有错误

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

    您正在根据开始日期和结束日期过滤财务报告。它将返回您的财务报告集合。所以你不能直接调用@financial_reports.to_csv。另一种方法可以将其作为方法的参数发送,例如

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

    在模型中

    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
    

    模板丢失-当您没有相应的视图文件时会发生错误

    检查您是否拥有参考 http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicast 中指定的 /app/views/products/index.xls.erb 文件

    【讨论】:

    • @Mathi,感谢您的帮助,但现在我收到错误 unexpected end 并在重新加载后 - undefined method key?' for nil:NilClass
    • 以前的错误仍然存​​在(即使我设置了条件where(:created_at =&gt; "1/08/2012".to_date.."10/08/2012".to_date)
    • 我用另一篇文章重写了代码,但是不知道怎么传params(
    猜你喜欢
    • 2023-03-16
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多