Showing posts with label excelsheet export in rails. Show all posts
Showing posts with label excelsheet export in rails. Show all posts

Wednesday, 20 February 2013

Giving name to excel sheet while exporting it- rails 3

You may want to give file name to your excelsheet when you are exporting it. Suppose you want to give the todays date and time as its name. Then do the following:

Suppose export is the method in which you have written the code for exporting excel sheet then do the following:


    def export
       time = Time.now
       time.strftime("%Y-%m-%d %H:%M:%S")
 
      respond_to do |format|
      format.html

      format.xls { headers["Content-Disposition"] = "attachment; filename=\"#{time}"+".xls"}
    end

Monday, 14 January 2013

Exporting table as Excel Sheet and CSV on ruby on rails

In this post I am not going to brief you on how to export any table as Excel Sheet and CSV in ruby on rails.
It can be found in this link--> Exporting as CSV and EXcel Sheet

I will address the problem which I faced while using it.

Problem

I followed  all the steps mentioned in the link and everything seems to be working fine.
There was no exception and even the download link was working fine.

However when I downloaded the excel file and opened it, the data in the files was not the content of the table . Rather the excel sheet was rendering the lists of objects like this-
#<Colleague:0x35e1e20>,
 #<Colleague:0x35e19d0>



Solution

In controller, instead of using @colleagues i.e the instance variable use the model name instead like this.

Note:- It may happen that you are able to export an excel sheet without this solution also. But if you are not  try this !!

Replace this: 

  format.csv { send_data @colleagues.to_csv }
  format.xls { send_data @colleagues.to_csv(col_sep: "\t") }
With

 format.csv { send_data Colleague.to_csv }
 format.xls { send_data Colleague.to_csv(col_sep: "\t") }

Some tips:
  • Make sure to restart the server after changing the config files.
  • Gems like spreadsheet are also available which can be used for this same purpose.