سؤال

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

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top