ruby-on-railsrubycsvamazon-s3axlsx

How to export active record data to excel file and save xlsx file into Amazon S3 bucket without storing it on local machine using ruby on rails


In our rails 6 project I want to export active record data to excel file and save xls file into S3 bucket without storing xls data on local db and send file link to email and provide download xls feature from email. Please help me.


Solution

  • 1. Create a model which holds a exported file

    # app/models/csv_export.rb
    
    class CsvExport < ApplicationRecord
      has_one_attached :file
      # ...
    end
    

    Configure ActiveStorage that it uses S3 as a provider. See https://medium.com/alturasoluciones/setting-up-rails-5-active-storage-with-amazon-s3-3d158cf021ff

    2. Create a export job which creates a new CsvExport with data

    # app/jobs/csv_export_job.rb
    require 'csv'
    
    class CsvExportJob < ApplicationJob
      queue_as :default
    
      def perform(csv_export_id)
        csv_export = CsvExport.find_by(id: csv_export_id)
        csv_export.file.attach \
          io: StringIO.new(csv_string), # add csv_string call here
          filename: filename
        # ...
      end
    
      private
    
      # ...
    
      CSV_COLUMNS = %w[id name email].freeze
    
      def csv_string
        CSV.generate(headers: true) do |csv|
          csv << CSV_COLUMNS
          # or whatever data you want to export
          User.all.each do |contact|
            csv << CSV_COLUMNS.map { |col| contact.send(col) }
          end
        end
      end
    end
    
    

    3. Trigger job

    e.g. from a controller action

    csv_export = CsvExport.create(status: :started)
    CsvExportJob.perform_later csv_export.id
    

    I hope these examples will bring you to the right direction. If you need detailed help you can look at this article https://railsbyexample.com/export-records-to-csv-files-using-activestorage/