Rails Axlsx Gem:如何在工作簿中的工作表之间切换

时间:2018-09-12 21:25:06

标签: ruby-on-rails excel axlsx

我正在写一个工作簿,其中对数组的每次迭代都向该工作簿添加新的工作表。

 a = [1,2,3,4]
    p = Axlsx::Package.new
    a.each do |arr|        
        p.workbook.add_worksheet(:name => "Name Sheet_#{arr}") do |sheet|
         sheet.add_row(["#","Name", "Status"]
         sheet.add_row(["1","ABC", 1]
         sheet.add_row(["2","XYZ", 0]
        end
        p.workbook.add_worksheet(:name => "Address Sheet_#{arr}") do |sheet|
         sheet.add_row(["#","Address", "Status"]
         sheet.add_row(["1","NYC", 0]
         sheet.add_row(["2","LA", 1]
        end
#add a summary worksheet

    end

现在,我想添加一个摘要表,其中将包含所有工作表中状态1的记录。摘要表只会被添加一次(Axlsx仍然会抛出重复的表错误)

1:Axlsx可以在工作簿中打开工作表并向其中添加行吗? 2:有什么方法可以检查工作簿中是否存在特定的工作表? (按工作表名称搜索)

1 个答案:

答案 0 :(得分:0)

您可以通过按工作表名称(必须是唯一的)进行选择来打开现有工作表。

1。 Axlsx可以在工作簿中打开工作表并向其添加行吗?

p = Axlsx::Package.new

# Create the worksheet
p.workbook.add_worksheet(:name => "Name Sheet_1") do |sheet|
    sheet.add_row ["#","Name", "Status"]
    sheet.add_row ["1","ABC", 1]
    sheet.add_row ["2","XYZ", 0]
end

# Select the worksheet
sheet = p.workbook.worksheets.select {|w| w.name == "Name Sheet_1"}.first
sheet.add_row [1, 2, 3]

2。有什么方法可以检查工作簿中是否存在特定的工作表? (按工作表名称搜索)

p = Axlsx::Package.new 

# Create the worksheet
p.workbook.add_worksheet(:name => "Name Sheet_1") do |sheet|
    sheet.add_row ["#","Name", "Status"]
    sheet.add_row ["1","ABC", 1]
    sheet.add_row ["2","XYZ", 0]
end

# Search for the worksheet by name   
p.workbook.worksheets.any? {|worksheet| worksheet.name == "Name Sheet_1"} # true
p.workbook.worksheets.any? {|worksheet| worksheet.name == "Name Sheet_2"} # false