palani
palani

Reputation: 4679

spreadsheet Rails 3 question

I have upgraded my rails 2.3.10 application into Rails 3.0.3. In my application i have the feature like user can download the data into excel.

My gem version : spreadsheet-0.6.4.1

I have declared gem version in Gemfile and Mime::Type.register_alias "application/excel", :xls in application.rb. and my excel generationg code as follows

<%

book = Spreadsheet::Workbook.new
 data = book.create_worksheet :name => 'myname'
 data.row(0).concat %w{name email}
 header_format = Spreadsheet::Format.new :color => :green, :weight => :bold
 data.row(0).default_format = header_format

@names.results_data.each_with_index { |n, i|

data.row(i+1).push n.name,n.email
}

blob = StringIO.new('')
book.write(file_blob)
-%><%=blob.string%>

My controller code is :

respond_to do |format|
      format.html
      format.rss
      format.xls {    
        view_output = render_to_string :action => "excel" << name
        send_data(view_output, :type=>"application/ms-excel", :filename => "name.xls")
      }

The problem is when click the excel link , it open up the excel window and its says in the popup 'name.xls[2] cann't be access. may be corrupted or read only ... i have changed all the possibilites like gem upgrade, mime-type change but no luck...

Can any one say what is the error

Upvotes: 1

Views: 2924

Answers (1)

Tim Snowhite
Tim Snowhite

Reputation: 3776

Two thoughts:

  1. There's no need for excel.xls.erb to be an erb file. You can easily put that in either a helper or another method in the current controller. I know the ERb semantics changed a bunch in rails 3, so this could be the cause of your errors.

     def render_to_xls(names, name = 'myname')
    
      book = Spreadsheet::Workbook.new
      data = book.create_worksheet :name => name
      data.row(0).concat %w{name email}
      header_format = Spreadsheet::Format.new :color => :green, :weight => :bold
      data.row(0).default_format = header_format
    
      names.results_data.each_with_index { |n, i|
    
         data.row(i+1).push n.name,n.email
      }  
      blob = StringIO.new('')
      book.write(blob)
      blob
    end
    

    And later, in your responder code:

        respond_to do |format|
          format.html
          format.rss
          format.xls {    
            send_data(render_to_xls(@names, name), :type=>"application/ms-excel", :filename => "name.xls")
          }
    
  2. Try doing a diff of a previous excel file against the current excel file and see if there are weird whitespace differences or anything like that.

Upvotes: 1

Related Questions