Commit 1aa4599a by liyijie

Add exportable logic

parent a5de4139
...@@ -2,10 +2,81 @@ module TalltyImportExport ...@@ -2,10 +2,81 @@ module TalltyImportExport
module Exportable module Exportable
extend ActiveSupport::Concern extend ActiveSupport::Concern
# export_headers / headers
# key: 属性的英文名
# name: 属性的中文名
# attr_type: 属性的类型
# format: excel是否需要特定的格式,目前主要是类似于身份证号,可以用string
# method: 本地调用的方法
included do included do
end end
module ClassMethods module ClassMethods
def export_records records
exportable_defaults
Axlsx::Package.new do |pack|
workbook = pack.workbook
# excel导出样式
alignment = { vertical: :center, horizontal: :center }
border = { color: '969696', style: :thin }
title1 = workbook.styles.add_style(alignment: alignment, border: border, sz: 16, b: true)
title2 = workbook.styles.add_style(alignment: alignment, border: border, bg_color: "2a5caa", sz: 16, fg_color: "fffffb")
title3 = workbook.styles.add_style(alignment: alignment.merge(wrap_text: true), border: border, sz: 14)
workbook.add_worksheet do |sheet|
if respond_to?(:first_header)
row_index = Axlsx.col_ref(headers.size - 1)
sheet.merge_cells("A1:#{row_index}1")
sheet.add_row [first_header], style: title1, height: 40
end
sheet.add_row _titles, style: title2, height: 39
records.each do |record|
row = []
@headers.each{ |header| row.push(handle_data(record, header)) }
sheet.add_row row, style: title3, height: @row_height, types: @headers.map{|header| header[:format]}
end
sheet.column_widths *@headers.map{|header| header[:width] || @width}
end
end
file_path = File.join(Rails.root, 'public', 'export')
FileUtils.mkdir_p(file_path) unless Dir.exist?(file_path)
file_name = "#{Time.now.strftime('%Y%m%d%H%M%S')}#{filename}.xlsx"
pack.serialize(File.join(file_path, file_name))
url = ActionController::Base.helpers.asset_url("/export/#{file_name}")
return url
end
def exportable_defaults(options = {})
options = options.with_indifferent_access
@row_height ||= options.delete(:row_height) || 35
@width ||= options.delete(:width) || 30
@headers = self.respond_to?(:export_headers) ? export_headers.with_indifferent_access : headers.with_indifferent_access
end
# 处理一个记录的数据
def handle_data record, header
if header[:method].present?
send(header[:method], record, header[:key])
else
record.send(header[:key])
end
rescue
''
end
# 根据数据类型 attr_type 进行数据的格式化
def handle_format data, header
case header[:attr_type].to_s
when 'datetime'
data ? data.strftime('%F %H:%M') : nil
when 'date'
data ? data.strftime('%F') : nil
end
end
end end
end end
end end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment