I am working with 'Axlsx' gem in rails , but didn't got how to protect some special column in that excel .
3 Answers
What you want to do is specify an unlocked style and apply it to all rows that should not be protected. I know it is a bit convoluted, but then so is the specification!
p = Axlsx::Package.new
wb = p.workbook
unlocked = wb.styles.add_style { locked: false }
wb.add_worksheet(name: 'Sheet Protection') do |sheet|
sheet.sheet_protection.password = 'fish'
sheet.add_row [1, 2 ,3] # These cells will be locked
sheet.add_row [4, 5, 6], style: unlocked # these cells will not!
end
p.serialize 'dont_touch_my_headers.xlsx'
The important thing to remember is that you need to specify a style for all non-header rows that includes
locked: false

- 2,430
- 1
- 19
- 18
You can specify locked in a style, then apply that style to the column at the end:
locked = wb.styles.add_style :locked => true
sheet.col_style 2, locked
I've not tested that. It combines a few examples. Here is an example of locking a single row:
https://github.com/randym/axlsx/blob/master/examples/example.rb#L571

- 2,095
- 14
- 14
-
Thanks a lot Mr. noel. But whenever i add sheet.sheet_protection.password = 'XYZ'. for protection with locked,unlocked it protected my whole axlsx. But i wants to protect only my header row not all. – Prashant Mishra Oct 01 '13 at 10:39
My solution was that I checked the sheet.sheet_protection
method and see the some useful method:
[5] pry(#<ProductsGrid>)> sheet.sheet_protection
=> #<Axlsx::SheetProtection:0x007f8a36173730
@auto_filter=true,
@delete_columns=true,
@delete_rows=true,
@format_cells=true,
@format_columns=true,
@format_rows=true,
@insert_columns=true,
@insert_hyperlinks=true,
@insert_rows=true,
@objects=false,
@password=nil,
@pivot_tables=true,
@scenarios=false,
@select_locked_cells=false,
@select_unlocked_cells=false,
@sheet=true,
@sort=true>
and used one of them, just like i use in the Microsoft Excel. Here below is my
unlocked = product_book.styles.add_style locked: false
product_sheet = product_book.add_worksheet(name: 'Product') do |sheet|
sheet.sheet_protection.password = 'password'
sheet.sheet_protection.select_locked_cells = true
sheet.add_row set_product_header, style: wrap_text
end
After inserting the row, apply style unlocked
the the rest of the rows

- 1,200
- 13
- 26
-
One comment: The flags (un)set the protection. To allow the autofilter on a protected sheet, you must set `auto_filter=false` (meaning the protection of the autofilter is off, the action is allowed). – knut Oct 01 '20 at 09:47
-
I don't set the option. I just want to show that there are options when we call this methods `sheet.sheet_protection` – Kiry Meas Oct 02 '20 at 09:38
-
1Yes, and this helped me a lot. I just wanted to help others and leave a hint, if they run into the same troubles then me. – knut Oct 02 '20 at 14:56