2016-08-16 151 views
0

我在我的應用程序中添加了CSV和Excel導出功能,但在下載文件後,它僅顯示此#<Axlsx::Worksheet:0x007f5d23708dc0>而不是電子表格中所需的數據。Excel導出不起作用

我還分享了我用過的方法和寶石。

這個出口,我已經創造下模塊導出一個單獨的控制器和一個單獨的類已安裝

require 'csv' 
require 'axlsx' 
# extend ActiveSupport::Concern 
# include Rails.application.routes.url_helpers 
module Export 
    class ParseError < ::StandardError; end 
    class ExportError < ::StandardError; end 
    class TimesheetExport 
    attr_accessor :error 

    def initialize(trackers, export_to='csv') 
     @trackers = trackers 
     @export_to = export_to 
    rescue ActiveRecord::RecordNotFound 
    end 

    def process 
     if [email protected] 
     @error = "Not Found" 
     return false 
     else 
     case @export_to 
      when "csv" 
      export_csv 
      when "xls" 
      export_xls 
      else 
      raise ExportError 
     end 
     end 
    end 

    def export_csv 
     columns = %w(Date Task Task_URL TimeSpent Log) 
     CSV.generate do |csv| 
     csv << columns 
     @trackers.each do |t| 
      csv << [t.created_at.to_s(:short_human_with_12hours), 
        t.task.name, 
        #project_task_url(t.task.project, t.task, host: AppConfig.app_url), 
        t.time_spent, 
        t.description ] 
     end 
     end 
    end 

    def export_xls 
     package = Axlsx::Package.new 
     workbook = package.workbook 
     workbook.add_worksheet(name: "Timesheet") do |sheet| 
     sheet.add_row ["Date", "Task Name","Time Spent","Log"] 
      @trackers.each do |t| 
      sheet.add_row [t.created_at.to_s(:short_human_with_12hours), 
          t.task.name, 
          t.time_spent, 
          t.description] 
     end 
     end 
    end 

寶石 -

gem 'axlsx', '= 2.0.1' 
gem 'axlsx_rails' 

這是辦法,我傳遞值來自出口控制器 -

@exporter = Export::TimesheetExport.new(user_trackers, params[:export_to]) 
    export_string = @exporter.process 
    if export_string 
     case params[:export_to] 
     when "csv" 
      send_data export_string, 
        type: 'text/csv; charset=iso-8859-1; header=present', 
        disposition: "attachment; filename=#{@exporter.file_name}" 
     when "xls" 
      send_data export_string, 
        type: 'application/xls; charset=iso-8859-1; header=present', 
        disposition: "attachment; filename=#{@exporter.file_name}" 
     end 
    else 
     flash[:alert] = @exporter.error 
     redirect_to timesheet_path 

回答

2

export_xls正在返回一個ruby對象,你需要返回文件流本身。

def export_xls 
     package = Axlsx::Package.new 
     workbook = package.workbook 
     workbook.add_worksheet(name: "Timesheet") do |sheet| 
     sheet.add_row ["Date", "Task Name","Time Spent","Log"] 
      @trackers.each do |t| 
      sheet.add_row [t.created_at.to_s(:short_human_with_12hours), 
          t.task.name, 
          t.time_spent, 
          t.description] 
     end 
     end 
     package.to_stream.read # Return the file stream to send_data 
    end