【问题标题】:Create multiple sheets that uses same template using rubyxl使用 ruby​​xl 创建多个使用相同模板的工作表
【发布时间】:2015-04-08 06:53:14
【问题描述】:

我有一个只有一张工作表(Sheet1)的 excel 模板。是否可以使用 ruby​​xl 生成在我的输出文件中使用 Sheet1 作为模板的多个工作表?

【问题讨论】:

    标签: ruby excel rubyxl


    【解决方案1】:

    我可以通过以下步骤实现这一点:

    1。解析 xlsx/xlsm 文件

    workbook = RubyXL::Parser.parse(File.join(Rails.root, "public", "template.xlsm")
    

    2。取工作表模板

    template = workbook[0]
    

    3。向工作簿添加新工作表

    worksheet = workbook.add_worksheet("Example")
    

    4。重复 sheet_data

    worksheet.sheet_data = template.sheet_data.dup
    worksheet.sheet_data.rows = template.sheet_data.rows.map do |row|
      next unless row
      new_row = row.dup
      new_row.worksheet = worksheet
      new_row.cells = row.cells.map{ |cell| next unless cell; new_cell = cell.dup; new_cell.worksheet = worksheet; new_cell }
      new_row
    end
    

    不幸的是 Marshal.dump 为 sheet_data 的单元格返回错误 no _dump_data is defined for class Nokogiri::XML::Namespace,所以我不得不编写这个肮脏的解决方法。

    5。复制您需要的所有其他内容

    worksheet.cols = Marshal.load(Marshal.dump(template.cols))
    worksheet.merged_cells = Marshal.load(Marshal.dump(template.merged_cells))
    

    更多属性请查看template.instance_variables

    您也可以删除模板

    workbook.worksheets.delete(template)
    

    并返回带有新工作表的工作簿

    send_data workbook.stream.string, filename: "example.xlsm", disposition: "attachment"
    

    ...在 Rails 控制器中

    或者直接保存到文件中

    workbook.write("path/to/desired/Excel/file.xlsx")
    

    【讨论】:

      【解决方案2】:
      template = RubyXL::Parser.parse 'path/to/template.xlsx'
      sheet1 = template.worksheets[0]
      sheet2 = template.worksheets[0]
      #your code manipulating sheet1, sheet2 etc.
      return RubyXL::Workbook.new [sheet1, sheet2]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-10
        • 1970-01-01
        • 2019-11-29
        • 2014-04-28
        • 2014-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多