Rails将excel文件的列映射到db列
我正在开发一个引擎,我正在使用Roo
gemparsing一个excel文件。 我面临的问题是,我不知道如何映射列。
例如,我的db-table
有列first_name
, last_name
, emp_id
,等等。但是我的excel文件可以有任何列名,例如它可以是fname
, lname
, e_id
, designation
或者它可以是FirstName
, LastName
, EmployeeId
等。
现在,我如何映射数据,以便将其存储在相应的列中。
我检查了这个问题,但我如何设置别名,因为我的Excel列标题可以是任何东西。 如果可以别名请告诉我,我可以做到这一点。 这是我第一次使用rails引擎。 另外我是新来的ruby。 任何帮助,将不胜感激。
如果excel列的顺序是固定的,那么你可以像这样存储数据:
@xls = Roo::Spreadsheet.open(file, extension: :xls) for i in 2..@xls.last_row Table.create(first_name: @xls.row(i)[1],last_name: @xls.row(i)[2],..) end
希望它能帮助你…
对于这种东西,我会使用一个服务对象。
class ImportExcel DEFAULT_MAPPING = { excel_col_name => db_colname }.freezy def initialize(mapping=nil, model_class=nil) @mapping = mapping || DEFAULT_MAPPING @model_class = model_class || DefaultModelClass end def import(excel_sheet) records = [] header = excel_sheet.first_row 2.upto(excel_sheet.last_row) do |line| record = @model_class.new records << record header.each_with_index do |name, col| record[@mapping[name]]= excel_sheet.row[line][col] end end records end end # Where ever importer = ImportExcel.new({ a: :b , c: :d}, MyModel) new_records = importer.import(sheet) new_records.map(&:save!)