import csv work with xlsx files
This commit is contained in:
parent
4c49e4d3fa
commit
aa3dbed95b
@ -32,11 +32,15 @@ class ImportCsv < ApplicationRecord
|
||||
|
||||
|
||||
after_create do
|
||||
|
||||
if file_is_csv?
|
||||
csv_text = File.read(self.file.path, :encoding => 'UTF-8')
|
||||
@csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
|
||||
|
||||
@csv.headers.each do |header|
|
||||
csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
|
||||
headers = csv.headers
|
||||
else
|
||||
xlsx = Roo::Spreadsheet.open(self.file.path, extension: :xlsx) # open spreadsheet
|
||||
headers = xlsx.row(1)
|
||||
end
|
||||
headers.each do |header|
|
||||
self.import_csv_headers << ImportCsvHeader.new(:name => header)
|
||||
|
||||
end
|
||||
@ -50,12 +54,15 @@ class ImportCsv < ApplicationRecord
|
||||
|
||||
end
|
||||
|
||||
|
||||
self.save
|
||||
|
||||
|
||||
end
|
||||
|
||||
|
||||
def file_is_csv?
|
||||
File.read(self.file.path, :encoding => 'utf-8').valid_encoding?
|
||||
end
|
||||
|
||||
|
||||
def charge
|
||||
|
||||
self.import_csv_elements.each do |e|
|
||||
@ -63,10 +70,12 @@ class ImportCsv < ApplicationRecord
|
||||
e.destroy
|
||||
end
|
||||
|
||||
csv_text = File.read(self.file.path, :encoding => 'UTF-8')
|
||||
@csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
|
||||
r = []
|
||||
@csv.each do |row|
|
||||
|
||||
if file_is_csv?
|
||||
csv_text = File.read(self.file.path, :encoding => 'UTF-8')
|
||||
csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
|
||||
csv.each do |row|
|
||||
line = {}
|
||||
self.import_csv_champs.each do |import_csv_champ|
|
||||
if import_csv_champ.header?
|
||||
@ -74,14 +83,30 @@ class ImportCsv < ApplicationRecord
|
||||
elsif import_csv_champ.value?
|
||||
eval "line['#{import_csv_champ.champ}'] = \"#{import_csv_champ.value}\""
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
r << line
|
||||
|
||||
end
|
||||
|
||||
return r
|
||||
else
|
||||
xlsx = Roo::Spreadsheet.open(self.file.path, extension: :xlsx) # open spreadsheet
|
||||
headers = xlsx.row(1) # get header row
|
||||
xlsx.each_with_index do |row, idx|
|
||||
line = {}
|
||||
next if idx == 0 # skip header
|
||||
# create hash from headers and cells
|
||||
data = Hash[[headers, row].transpose]
|
||||
self.import_csv_champs.each do |import_csv_champ|
|
||||
# raise
|
||||
if import_csv_champ.header?
|
||||
eval "line['#{import_csv_champ.champ}'] = data[\"#{import_csv_champ.header}\"]"
|
||||
elsif import_csv_champ.value?
|
||||
eval "line['#{import_csv_champ.champ}'] = \"#{import_csv_champ.value}\""
|
||||
end
|
||||
end
|
||||
r << line
|
||||
end
|
||||
return r
|
||||
end
|
||||
end
|
||||
|
||||
def load
|
||||
|
Reference in New Issue
Block a user