Export XLSX

This commit is contained in:
Nicolas Bally 2020-09-18 08:59:28 +02:00
parent 9f8ecec536
commit a9d5755886

View File

@ -402,42 +402,47 @@ class Admin::PCustomersController < ApplicationController
end
@csv = CSV.generate(:headers => true, :col_sep => ";") do |csv|
csv << @headers
@p_customers.each do |p_customer|
line = []
@columns.each do |column|
xlsx_package = Axlsx::Package.new
wb = xlsx_package.workbook
wb.add_worksheet(name: "import") do |sheet|
sheet.add_row @headers
if (p_customer.respond_to?("csv_"+column.to_s))
line << p_customer.send("csv_"+column.to_s)
elsif (p_customer.respond_to?(column))
if p_customer.send(column.to_s).class.to_s == "BigDecimal"
line << p_customer.send(column.to_s).to_s.gsub('.', ',')
@p_customers.each do |p_customer|
line = []
@columns.each do |column|
if (p_customer.respond_to?("csv_"+column.to_s))
line << p_customer.send("csv_"+column.to_s)
elsif (p_customer.respond_to?(column))
if p_customer.send(column.to_s).class.to_s == "BigDecimal"
line << p_customer.send(column.to_s).to_s.gsub('.', ',')
else
line << p_customer.send(column.to_s)
end
else
line << p_customer.send(column.to_s)
line << column.to_s
end
else
line << column.to_s
end
end
end
csv << line
sheet.add_row line, types: line.map{|t| self.cell_type_from_value(t)}
end
end
end
@data_to_send = @csv
@final_file = "#{Rails.root}/private_medias/export-inscrits-#{Time.now.to_s.to_slug}.xlsx"
send_data @data_to_send.to_s, :filename => "export-csv.csv", :type => :csv #, :type => 'text/csv; charset=iso-8859-1; header=present'
#"\uFEFF" +
xlsx_package.serialize(@final_file)
send_file @final_file
}
@ -447,6 +452,30 @@ class Admin::PCustomersController < ApplicationController
end
end
def cell_type_from_value(v)
if v.is_a?(Date)
:date
elsif v.is_a?(String)
:string
elsif v.is_a?(Time)
:time
elsif v.is_a?(TrueClass) || v.is_a?(FalseClass)
:boolean
elsif v.to_s =~ /\A[+-]?\d+?\Z/ #numeric
:integer
elsif v.to_s =~ /\A[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\Z/ #float
:float
# \A(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[0-1]|0[1-9]|[1-2][0-9])
# T(2[0-3]|[0-1][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?
# (Z|[+-](?:2[0-3]|[0-1][0-9]):[0-5][0-9])?\Z
elsif v.to_s =~/\A(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[0-1]|0[1-9]|[1-2][0-9])T(2[0-3]|[0-1][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[0-1][0-9]):[0-5][0-9])?\Z/
:iso_8601
else
:string
end
end
def show
@p_customer = PCustomer.find(params[:id])