我有一个excel模板,它只有一个工作表(Sheet1)。是否可以使用rubyxl生成多个工作表,在工作文件中使用Sheet1作为模板?
答案 0 :(得分:0)
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]
答案 1 :(得分:0)
我能够通过以下步骤实现这一目标:
workbook = RubyXL::Parser.parse(File.join(Rails.root, "public", "template.xlsm")
template = workbook[0]
worksheet = workbook.add_worksheet("Example")
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
,所以我不得不编写这种肮脏的解决方法。
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")