To prevent Formula Injection vulnerabilities, you can escape formulas at multiple levels of granularity within caxlsx. Escaping ensures that strings starting with characters like = are treated as text rather than executable formulas.
You can set the escape_formulas property at the following scopes:
| Scope | Implementation Example | Notes |
|---|
| Global | Axlsx.escape_formulas = true | Affects worksheets created after setting. Does not affect existing worksheets. |
| Workbook | workbook.escape_formulas = true | Affects child worksheets added after setting. Does not affect existing child worksheets. |
| Worksheet | workbook.add_worksheet(name: 'Name', escape_formulas: true) | Sets escaping for the specific worksheet. |
| Worksheet | worksheet.escape_formulas = true | Affects child rows/cells added after setting. Does not affect existing child rows/cells. |
| Row | worksheet.add_row([...], escape_formulas: [true, false]) | Can be a Boolean (applies to all cells in row) or an Array (one value per cell). |
| Row | row.escape_formulas = [true, false] | Changes the escape_formulas value on existing cells. Can be a Boolean or an Array. |
| Cell | cell.escape_formulas = true | Sets escaping for a specific cell. |
require 'axlsx'
# Global setting
Axlsx.escape_formulas = true
p = Axlsx::Package.new
bw = p.workbook
bw.add_worksheet(name: 'Escaping Formulas') do |sheet|
# Apply to all cells in the row
sheet.add_row [1, 2, 3, '=SUM(A2:C2)'], escape_formulas: true
# Apply per-cell using an array
sheet.add_row [
'=IF(2+2=4,4,5)',
'=IF(13+13=4,4,5)',
'=IF(99+99=4,4,5)'
], escape_formulas: [true, false, true]
# Modify an existing cell
sheet.rows.first.cells.first.escape_formulas = false
end
p.serialize 'escape_formula_example.xlsx'