Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

caxlsx_rails

> 编程语言
Open source

A Rails plugin to provide templates for the axlsx gem

762 stars0 likes1 views
WebsiteGitHub

About

A Rails plugin to provide templates for the axlsx gem

Notice: axlsx_rails renamed to caxlsx_rails

This gem has been renamed to match other gems in the Axlsx community organization: https://github.com/caxlsx

Axlsx-Rails — Spreadsheet templates for Rails

Notice: Community Axlsx Organization

To better maintain the Axlsx ecosystem, all related gems have been forked or moved to the following community organization:

https://github.com/caxlsx

Join the Caxlsx Slack channel

Installation

In your Gemfile:

ruby
gem 'caxlsx'
gem 'caxlsx_rails'

See previous installations if needed.

Requirements

  • Tested on Rails 6.1, 7.x, and 8.x.
  • Supported Ruby versions: 2.6, 2.7, 3.x, and 4.0
  • Minimum Caxlsx version: 4.0

FYI

  • This gem depends on caxlsx. See the blog or the examples page for usage.
  • Check out axlsx_styler by sakovias for easier styles and borders!

Usage

Axlsx-Rails provides a renderer and a template handler. It adds the :xlsx format and parses .xlsx.axlsx templates. This lets you take all the caxlsx code out of your controller or model and place it inside the template, where view code belongs! See this blog post for a more complete walkthrough.

Controller

To use Axlsx-Rails set your instance variables in your controller and configure the response if needed:

ruby
class ButtonController  'cover_sheet', :locals => {:wb => wb}
wb.add_worksheet(name: "Content") do |sheet|
  sheet.add_row ['Content']
end

With the partial simply using the passed variables:

ruby
wb.add_worksheet(name: "Cover Sheet") do |sheet|
  sheet.add_row ['Cover', 'Sheet']
end

Mailers

To use an xlsx template to render a mail attachment, use the following syntax:

…
  • If the route specifies or suggests the :xlsx format you do not need to specify formats or handlers.
  • If the template (users/export) can refer to only one file (the xlsx.axlsx template), you do not need to specify handlers, provided the formats includes :xlsx.
  • Specifying the encoding as 'base64' can avoid UTF-8 errors.

Scripts

To generate a template within a script, you need to instantiate an ActionView context. Here are two gists showing how to perform this:

  • Using rails runner
  • Without rails runner

Testing

There is no built-in way to test your resulting workbooks / templates. But here is a piece of code that may help you to find a way.

First, create a shared context

…

Include it in your spec files:

…

Matchers used

…

Troubleshooting

Mispellings

It is easy to get the spelling wrong in the extension name, the format.xlsx statement, or in a render call. Here are some possibilities:

  • If it says your template is missing, check that its extension is .xlsx.axlsx.
  • If you get the error uninitialized constant Mime::XSLX you have used format.xslx instead of format.xlsx, or something similar.

Using axlsx_rails in API mode

In API mode Rails does not include ActionView, so axlsx_rails will not work. To render axlsx_rails templates you must include ActionView::Rendering in your controller and override render_to_body:

ruby
class MyController < ActionController::API
  include ActionView::Rendering

  def show
    respond_to do |format|
      format.xlsx
    end
  end

  private

  def render_to_body(options)
    _render_to_body_with_renderer(options) || super
  end
end

See issue 107

Mailer Attachments: No content, cannot read, Invalid Byte Sequence in UTF-8

If you are having problems with rendering a template and attaching it to a template, try a few options:

  • Make sure the attachment template does not have the same name as the mailer.
  • After you have rendered the template to string, and before you call the mailer, execute self.instance_variable_set(:@_lookup_context, nil). If you must do this, please open an issue.
  • If you get Invalid Byte Sequence in UTF-8, pass encoding: 'base64' with the attachment:
ruby
class UserMailer < ActionMailer::Base
  def export(users)
    xlsx = render_to_string handlers: [:axlsx], formats: [:xlsx], template: "users/export", locals: {users: users}
    attachments["Users.xlsx"] = {mime_type: Mime[:xlsx], content: xlsx, encoding: 'base64'}
    # For Rails 4 use Mime::XLSX
    # attachments["Users.xlsx"] = {mime_type: Mime::XLSX, content: xlsx, encoding: 'base64'}
    # self.instance_variable_set(:@_lookup_context, nil) # If attachments are rendered as content, try this and open an issue
    ...
  end
end

If you get these errors, please open an issue and share code so the bug can be isolated. Or comment on issue #29 or #25.

The unparsed template is returned, or something similar

Have you followed other tutorials for serving Excel from Rails? Have you declared the MIME type already? These may be incompatible with caxlsx_rails (which declares the MIME type for you.) Remove any vestiges of other tutorials from your code and try again.

Generated Files Can't Be Opened or Invalid Byte Sequence in UTF-8

Both these errors appear to be caused by Rails applying a layout to the template. Passing layout: false to render :xlsx should fix this issue. Version 0.5.0 attempts to fix this issue.

If you get this error, please open an issue and share code so the bug can be isolated.

Rails 4.2 changes

Before Rails 4.2 you could call:

ruby
  render xlsx: "users/index"

And caxlsx_rails could adjust the paths and make sure the template was loaded from the right directory. This is no longer possible because the paths are cached between requests for a given controller. As a result, to display a template in another directory you must use the :template parameter (which is normal Rails behavior anyway):

ruby
  render xlsx: "index", template: "users/index"

If the request format matches you should be able to call:

ruby
  render "users/index"

This is a breaking change if you have the old syntax!

Turbolinks

If you are using turbolinks, you may need to disable turbolinks when you link to your spreadsheet:

ruby
# turbolinks 5:
link_to 'Download spreadsheet', path_to_sheet, data: {turbolinks: false}

Rails 7 Unknown Format

In Rails 7, if you get an error of "Unknown Format" you may need to add (format: "xlsx") to the named route.

A clue to the "format" that Rails is responding with is to look at your log file or console after you click the HTML link or submit your form. You should see Processing by Controller#action as XLSX.

Code Examples

Scenario 1 - HTML Link within index.html.erb

ruby
link_to "Download as Excel", my_named_route_path(format: "xlsx")

Scenario 2 - Using form_with()

ruby
form_with method: :post, url: my_named_route_path(format: :xlsx) do |f|

What to do

If you are having problems, try to isolate the issue. Use the console or a script to make sure your data is good. Then create the spreadsheet line by line without Axlsx-Rails to see if you are having caxlsx problems. If you can manually create the spreadsheet, create an issue and we will work it out.

Dependencies

  • Rails
  • caxlsx

Authors

  • Noel Peden

Contributors

Many thanks to contributors:

  • randym
  • sugi
  • envek
  • engwan
  • maxd
  • firien
  • kaluzny
  • sly7-7
  • kodram
  • JohnSmall
  • BenoitHiller

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言