Module: IprogExportModelToXlsx
- Defined in:
- lib/iprog_export_model_to_xlsx.rb,
lib/iprog_export_model_to_xlsx/version.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- VERSION =
"0.1.2"
Instance Method Summary collapse
Instance Method Details
#export_to_xlsx(file_path = nil, options = {}) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/iprog_export_model_to_xlsx.rb', line 9 def export_to_xlsx(file_path = nil, = {}) exclude_columns = [:exclude_columns] || [] limit = [:limit] conditions = [:conditions] || ->(scope) { scope } sheet_name = [:sheet_name] || self.name column_formats = [:column_formats] || {} progress_callback = [:progress_callback] || default_progress_callback filtered_file_path = file_path || "#{self.name.to_s.downcase}s.xlsx" attributes = self.attribute_names - exclude_columns workbook = Axlsx::Package.new workbook.workbook.add_worksheet(name: sheet_name) do |sheet| sheet.add_row(attributes.map(&:upcase)) scope = self.all scope = conditions.call(scope) scope = scope.limit(limit) if limit total_records = scope.size scope.each_with_index do |record, index| row_data = record.attributes.slice(*attributes).map do |attr, value| column_formats[attr] ? column_formats[attr].call(value) : value end sheet.add_row(row_data) progress_callback.call(index + 1, total_records) end end workbook.serialize(filtered_file_path) rescue StandardError => e raise Iprog::Arde::Error, "Failed to export to XLSX: #{e.}" end |