Search code examples
ruby-on-rails-3axlsx

How do I protect header rows but allow to enter new rows using AXLSX?


I am working with 'Axlsx' gem in rails , but didn't got how to protect some special column in that excel .


Solution

  • 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