使用gem axlsx,如何在一个程序中创建多个工作簿?

时间:2015-05-13 23:34:25

标签: ruby-on-rails axlsx

使用基本的axlsx代码,我需要创建一个工作簿,关闭它并在同一个程序中创建一个新的工作簿。工作簿将生成名称,并将创建变量编号。此时,我可以创建我需要的工作表,但根据我的要求,我有重复的工作表名称。无论如何,我需要创建多个文件。

我正在使用基本的github示例:

Axlsx::Package.new do |p|
  p.workbook.add_worksheet(:name => "Pie Chart") do |sheet|
    sheet.add_row ["Simple Pie Chart"]
    %w(first second third).each { |label| sheet.add_row [label, rand(24)+1] }
    sheet.add_chart(Axlsx::Pie3DChart, :start_at => [0,5], :end_at => [10, 20], :title => "example 3: Pie Chart") do |chart|
      chart.add_series :data => sheet["B2:B4"], :labels => sheet["A2:A4"],  :colors => ['FF0000', '00FF00', '0000FF']
    end
  end
  p.serialize('simple.xlsx')
end

1 个答案:

答案 0 :(得分:0)

运行代码,简化,作为示例。它使用to_stream方法,但似乎关键是为每个工作簿使用不同的包。使用带有块的to_stream方法会在文件完成时关闭文件。

class Unload < ApplicationController
  require 'axlsx'

  package = Axlsx::Package.new
  workbook = package.workbook

  puts "Companies"
  workbook.add_worksheet(name: "Companies") do |sheet|
    sheet.add_row ["Name", "Domain", "Prefix"]
    Company.all.each do |a|
      sheet.add_row [a.name, a.domain, a.prefix]
    end
  end

  stream = package.to_stream()
  File.open('db/unloaded/Joint.xlsx', 'wb') { |f| f.write(stream.read) }
  workbook = nil
  stream   = nil
  package  = nil

  Company.all.each do |c|
    puts "Company is: " << c.name
    ActsAsTenant.with_tenant(c) do
      c.package  = Axlsx::Package.new
      c.workbook = c.package.workbook
      company_name = c.blank? ? "Invalid Company" : c.name

      puts "Associates for #{company_name}"
      c.workbook.add_worksheet(name: "Associates") do |sheet|
        sheet.add_row ["Logon", "Name", "Email", "Cell", "Company"]
        Associate.all.each do |a|
          sheet.add_row [a.logon, a.name, a.email, a.cell, company_name]
        end
      end

      puts "Serializing for #{company_name}"
      stream = c.package.to_stream()
      File.open("db/unloaded/#{company_name}.xlsx", 'wb') { |f| f.write(stream.read) }
      c.workbook = nil
      stream     = nil
      c.package  = nil

    end
  end

end