tungsten_carbide
tungsten_carbide

Reputation: 555

How to write xls to tmp folder

I followed the railscasts tutorial on how a render an excel file (http://railscasts.com/episodes/362-exporting-csv-and-excel). We already have a lot of code on it so I'm trying to avoid rewriting by using a gem. How can I make it write to the rails /temp directory instead of letting the user download it? After it gets generated, I'll just attach it to an email and send to the user instead of letting the user wait for a long time. My problem now is how to write to the temp directory.

def mymethod
  @products = Product.order(:name)

  respond_to do |format|
    format.xls
  end
end

We are using rails 3.2.

Upvotes: 1

Views: 1380

Answers (1)

C dot StrifeVII
C dot StrifeVII

Reputation: 1885

This is a pretty general example of how to write a CSV to the tmp file

require 'csv'

def my_method
  @products = Product.order(:name)

  product_csv = CSV.generate do |csv|
          #you have to add values to CSVs inside arrays
          csv << %w(column_name1 coulmn_name2 column_name3)

          @products.each do |pd|
            csv << [pd.name,
                    pd.price,
                    pd.product_line]
          end
        end

  File.open("tmp/product.xls", 'w:UTF-8') {|file| file.write(product_csv)}
end

Upvotes: 1

Related Questions