【发布时间】:2015-04-08 06:53:14
【问题描述】:
我有一个只有一张工作表(Sheet1)的 excel 模板。是否可以使用 rubyxl 生成在我的输出文件中使用 Sheet1 作为模板的多个工作表?
【问题讨论】:
我有一个只有一张工作表(Sheet1)的 excel 模板。是否可以使用 rubyxl 生成在我的输出文件中使用 Sheet1 作为模板的多个工作表?
【问题讨论】:
我可以通过以下步骤实现这一点:
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")
【讨论】:
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]
【讨论】: