The Following gets you and xml Excel file. So the client needs a
newer version of excel.
in your controller
def export
@name = “Decay”
@items = LkDecayClassDwd.find(:all)
headers[‘Content-Type’] = “application/vnd.ms-excel”
headers[‘Content-Disposition’] = ‘attachment; filename="’+@name
+‘-’+Date.today.strftime+‘.xls"’
headers[‘Cache-Control’] = ‘’
render :layout => false , :template => “shared/export”
end
as export.rxml view
xml.instruct! :xml, :version=>“1.0”, :encoding=>“UTF-8”
xml.Workbook({
‘xmlns’ => “urn:schemas-microsoft-com:office:spreadsheet”,
‘xmlns:o’ => “urn:schemas-microsoft-com:office:office”,
‘xmlns:x’ => “urn:schemas-microsoft-com:office:excel”,
‘xmlns:html’ => “HTML 4.01 Specification”,
‘xmlns:ss’ => “urn:schemas-microsoft-com:office:spreadsheet”
}) do
xml.Styles do
xml.Style ‘ss:ID’ => ‘Default’, ‘ss:Name’ => ‘Normal’ do
xml.Alignment ‘ss:Vertical’ => ‘Bottom’
xml.Borders
xml.Font ‘ss:FontName’ => ‘Verdana’
xml.Interior
xml.NumberFormat
xml.Protection
end
xml.Style ‘ss:ID’ => ‘s22’ do
xml.NumberFormat ‘ss:Format’ => ‘General Date’
end
end
xml.Worksheet ‘ss:Name’ => @name do
xml.Table do
# Header
xml.Row do
get_column_names_in_hash(@items[0],Hash.new).sort.each do |key,value|
xml.Cell do
xml.Data value, ‘ss:Type’ => ‘String’
end
end
end
# Rows
for item in @items
xml.Row do
get_columns_in_hash(item,Hash.new).sort.each do |key,value|
xml.Cell do
xml.Data value, ‘ss:Type’ => ‘String’
end
end
end
end
end
end
end
and in the helper or you could replace the above calls to
get_column_names_in_hash and get_columns_in_hash hashes of each row
the following two functions make use of strict adherence to the
rails naming conventions for table and
#column names. Columns that end in _id are assumned to connect to
tables that are of the same name as foreign
#keys. This allows for the returning of all connected data for a
table recored to be returned. For any
record you can find related tables by looking for columns that
end in _id. For each of these related tables
you can return their data and any related table. Using this you
can retreive all the related data for a record
as long as it is up the tree. Data that belongs to tables that
connect back to this table are not found because
this table does not know of the relationship
def get_columns_in_hash(item,my_hash)
for column in item.class.columns do
if column.name =~ /(.*)(id)$/
my_hash.merge!( get_columns_in_hash(item.send
(Inflector.underscore(Regexp.last_match(1))),my_hash))
elsif column.name =~ /(id)$/
nil
else
my_hash[Inflector.underscore(item.class)+''+column.name]=
item.send(column.name)
end
end
my_hash
end
def get_column_names_in_hash(item,my_hash)
for column in item.class.columns do
if column.name =~ /(.*)(id)$/
my_hash.merge!( get_column_names_in_hash(item.send
(Inflector.underscore(Regexp.last_match(1))),my_hash))
elsif column.name =~ /(id)$/
nil
else
my_hash[Inflector.underscore(item.class)+'‘+column.name]=
Inflector.underscore(item.class)+’_'+column.name
end
end
my_hash
end