如何将数据转换为Excel文件

时间:2017-01-10 07:28:20

标签: ruby-on-rails ruby excel csv xls

我正在使用CSV类将数据转换为基于http://railscasts.com/episodes/362-exporting-csv-and-excel的Excel文件。

下载Excel文件后,我不会使用过滤器更新我在网页上看到的最新数据。我的Excel文件包含首次加载页面时显示的数据。

我试图调试问题并尝试其他宝石,如xlsx_writer,得到相同的结果:

def commission_report
   today = Date.today
   if params[:from_date].present?
     from_date = params[:from_date]
     to_date = params[:to_date]
   elsif params[:filter] == 'monthly'
     to_date = today
     from_date = today - 30
   else
     to_date = today
     from_date = today - 7
   end
   @commissions_report = UserOrderHistory.select("user_order_histories.*,SUM(user_order_histories.revenue_sharing) as revenue_total, restaurants.restaurant_name, managers.username,revenue_sharings.revenue").joins("LEFT JOIN revenue_sharings ON revenue_sharings.restaurant_id = user_order_histories.restaurant_id").joins("LEFT JOIN restaurants ON restaurants.id = user_order_histories.restaurant_id").joins("LEFT JOIN managers ON managers.id =   restaurants.manager_id").where("user_order_histories.status != ''").where("revenue_sharing > 0").group("user_order_histories.restaurant_id,user_order_histories.deduction_date").where("user_order_histories.deduction_date BETWEEN ? AND ?",from_date,to_date).order(sort_column + " " + sort_direction)
   @commissions_report = @commissions_report.as_json
   @commissions_report = Kaminari.paginate_array(@commissions_report).page(params[:page]).per(10)
  #  raise @commissions.inspect
   respond_to do |format|
     format.html
     format.csv { send_data @commissions_report.to_csv }
     format.xls #{ send_data @commissions_report.to_csv(col_sep:     "\t") }
   end

 end

2 个答案:

答案 0 :(得分:1)

这是因为当你点击:

@products = Product.order(:name)

它转到产品控制器中的索引方法,并且在该方法中,您再次从数据库中获取所有记录:

format.csv { send_data @filtered_products.to_csv }

所以你要做的就是将过滤产品的集合传递给CSV格式的响应。像这样:

$("#Your-Input").on('keypress', function() {
    $.ajax({
        url: 'http://www.somehost.ru',
        dataType: "json",
        data: {
            text: $("#Your-Input").val()
        }
    })
    .done(function(result) {
        //your handler here
    });
});

答案 1 :(得分:1)

当您进行过滤后的CSV请求时,不会解析参数:

EntityType

这样你的参数就会再次送回你的控制器。