I needed this gem for one of my projects, I liked the capability and simplicity of it. In this quick tutorial, I will show how you can create a simple XLS template on your web app.
So let's get into this:Setup:
1. Install Caxlsx
ruby gem to your Rails project by following the guidance in the link.
2. We will also need something like Tempfile. This will help us to create files in the memory rather than saving it on the hard drive.
3. Ready Caxlx template. It can be dynamic rows/data or static depends on your needs.Steps:
1. Create a caxlx helper. Now it can be a different implementation. In my project, all business logic goes to app/models, where the ActiveRecord models are in app/models/ar. Warning this is not a standard approach you can use a regular app/helper folder. The following example will build a simple Axlsx object with 3 rows - 'First, Second, Third' and render them into the virtual file 'Tempfile':
class TemplateBulderLogic < BusinessLogic
p = Axlsx::Package.new
wb = p.workbook
rows = ['First', 'Second', 'Third']
wb.add_worksheet(name: 'My Form') do |sheet|
p.serialize(file = prepare_file('my_template').path)
temp_file = Tempfile.new([file_name, '.xlsx'], encoding: 'ascii-8bit')
2. Controller. We will need to add logic to the controller.
3. Don't forget to create a simple get route to the create_xls_template.
4. View. All we need is to add a link_to tag to the route we created in step 3:
<%= link_to 'Download XLS Template', create_xls_template_path %>