update menu import and export

This commit is contained in:
Aung Myo
2018-03-19 18:13:38 +06:30
parent 919846ef5c
commit ca817197d9
9 changed files with 155 additions and 15 deletions

View File

@@ -1,4 +1,6 @@
class Menu < ApplicationRecord
require 'spreadsheet'
has_many :menu_categories, dependent: :destroy
validates_presence_of :name, :valid_days, :valid_time_from, :valid_time_to
@@ -34,7 +36,7 @@ class Menu < ApplicationRecord
def self.to_csv
m_attributes = %w{name is_active valid_days valid_time_from valid_time_to created_by created_at updated_at}
CSV.generate(headers: true) do |csv|
CSV.generate(headers: true, row_sep: "\r\n") do |csv|
csv << m_attributes
menu = Menu.all
menu.each do |user|
@@ -44,9 +46,41 @@ class Menu < ApplicationRecord
end
def self.import(file)
CSV.foreach(file.path, headers:true) do |row|
Menu.create! row.to_hash
end
spreadsheet = Roo::Spreadsheet.open(file.path)
puts spreadsheet.info
spreadsheet = Roo::Excelx.new(file.path)
puts spreadsheet.info
# Use the extension option if the extension is ambiguous.
spreadsheet = Roo::Spreadsheet.open(file.path, extension: :xlsx)
puts spreadsheet.info
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header,spreadsheet.row(i)].transpose]
menu = Menu.new
menu.name = row["name"]
menu.is_active = row["is_active"]
menu.valid_days = row["valid_days"]
menu.valid_time_from = row["valid_time_from"]
menu.valid_time_to = row["valid_time_to"]
menu.created_by = row["created_by"]
menu.save
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::CSV.new(file.path,nil,:ignore)
when ".xls" then Roo::Excel.new(file.path,nil,:ignore)
when ".xlsx" then Roo::Excelx.new(file.path,nil,:ignore)
else raise "Unknown File type: #{original_filename}"
end
end
end