2017-02-23 68 views
1

我使用axlsx gem將數據從Ruby/Rails導出到Excel中。Axlsx Ruby Gem - 使用自定義值創建下拉列表

我需要添加一個下拉菜單自定義值 - 值1,值2,值3等。以下是我試過

excel = Axlsx::Package.new 
wb = excel.workbook 

wb.add_worksheet(name: "sample_sheet") do |sheet| 
    sheet.add_data_validation("A1:A100", { 
     :type => :list, 
     :formula1 => "value1 value2 value3", 
     :showDropDown => false, 
     :showErrorMessage => true, 
     :errorTitle => '', 
     :error => 'Please use the dropdown selector to choose the value', 
     :errorStyle => :stop, 
     :showInputMessage => true, 
     :prompt => 'Choose the value from the dropdown' 
    }) 
end 

excel.serialize('sample_excel.xlsx') 

的代碼創建了Excel中的代碼,但是當我打開它,我得到這個Excel錯誤excel error 這些值不會添加到下拉列表中。

或者,

:formula1 => "B1:B2" 

正常工作,它增加了的B1和B2的內容的下拉。在我的用例中,我需要添加自定義值,它們不存儲在Excel表格中。

什麼是在數據驗證下拉菜單中添加自定義值的正確方法?請幫助。

+0

你解決呢? –

+0

@RareFever結帳我的答案。 –

回答

1

似乎無法在公式中指定值,但以下解決方案將適用於您的情況。

.axlsx文件添加另一張紙,讓您的自定義的值:

months_sheet = wb.add_worksheet(:name => 'DropDown Values') { |ws| ws.sheet_protection.password = 'pa55w0rd' } 
months_sheet.add_row ['value1', 'value2', 'value3'] 

然後更改您的代碼:

wb.add_worksheet(name: "sample_sheet") do |sheet| 
    sheet.add_data_validation("A1:A100", { 
     :type => :list, 
     :formula1 => "'DropDown Values'!A$1:C$1", 
     :showDropDown => false, 
     :showErrorMessage => true, 
     :errorTitle => '', 
     :error => 'Please use the dropdown selector to choose the value', 
     :errorStyle => :stop, 
     :showInputMessage => true, 
     :prompt => 'Choose the value from the dropdown' 
    }) 
end 

$ s的A$1:A$100necessary

+0

謝謝亞歷山大。我已經考慮過這一點,但我不能使用額外的表格或將其他值隱藏起來。我想知道Axlsx gem atall是否允許在下拉菜單中使用自定義值。 –