ROR - Excel Export Example


#1

If you are running on Windows you can use create and read speadsheets
using the ‘win32ole’ require

This sample should give you the basic idea

def export
require ‘win32ole’

  @sort_by = 'last_name'
  current_user = 'steve'
  @records = Contact.find(
      :all,
      :conditions => ["created_by = ?",

self.current_user.login.to_s] #,
#:order => @sort_by
)

# Creates OLE object to Excel
excel = WIN32OLE.new("excel.application")

# Create the chart
excel['Visible'] = TRUE;
excel.DisplayAlerts = false       #Supress's Excel warnings

workbook = excel.Workbooks.Add();
excel.Range("a1")['Value'] = 'First Name';
excel.Range("b1")['Value'] = 'Last Name';
excel.Range("c1")['Value'] = 'Middle Name';
excel.Range("d1")['Value'] = 'Name';

# add extra stuff down here
line_count = 1

@records.each do | contact |
    line_count = line_count + 1
    excel.Range("a" + line_count.to_s.strip  )['Value'] =

contact.first_name.to_s
excel.Range(“b” + line_count.to_s.strip )[‘Value’] =
contact.last_name.to_s
excel.Range(“c” + line_count.to_s.strip )[‘Value’] =
contact.middle_name.to_s
excel.Range(“d” + line_count.to_s.strip )[‘Value’] =
(contact.first_name.to_s + " " + contact.middle_name.to_s + " " +
contact.last_name.to_s).strip

  end

#  Here are some common file formats:
xlCSV=6
xlCSVMac=22
xlCSVMSDOS=24
xlCSVWindows=23
xlCurrentPlatformText=-4158
xlExcel9795=43
xlTextMSDOS=21
xlTextPrinter=36
xlTextWindows=20

workbook.SaveAs 'contacts_export.csv', xlCSV
excel.Quit
excel = nil   #release the excel object
GC.start      #call Garbage collector

end


#2

steve wrote:

If you are running on Windows you can use create and read speadsheets
using the ‘win32ole’ require

This sample should give you the basic idea

def export
require ‘win32ole’

  @sort_by = 'last_name'
  current_user = 'steve'
  @records = Contact.find(
      :all,
      :conditions => ["created_by = ?",

self.current_user.login.to_s] #,
#:order => @sort_by
)

As server side solution, it does not scale at all.

Regards,

rp8

http://competo.com