ruby 使用axlsx导出excel 图片
1.在Gemfile添加
gem 'axlsx'
gem 'axlsx_rails'
2.在controller中添加
respond_to do |format|
format.xlsx {
response.headers[
'Content-Disposition'
] = "attachment; filename=此处为导出文件名称.xlsx"
}
format.html
end
3.在view层添加 xxxx.xlsx.axlsx
wb = xlsx_package.workbook
wb.add_worksheet(name: "此处为创建sheet名称") do |sheet|
header = wb.styles.add_style({:alignment => {:horizontal => :center, :vertical => :center, :wrap_text => true}})
// horizontal:水平对其方式, vertical: 垂直对其方式,wrap_text: 自动换行
sheet.add_row ["图", "字段1", "字段2", "字段3", "字段4" ....], :style => header
Array.each_with_index do |arr, idx|
height = 150
img_height = 120
// 仅支持'gif', 'jpeg', 'png', 'jpg' 后缀图片
如需要图片等比例显示则通过IMagick获取图像属性
img = Magick::Image.read("#{Rails.root}/#{图片路径}").first rescue nil
if img
img_height = (img.base_rows / (img.base_columns.to_i == 0 ? 1 : img.base_columns/200.0)).to_i
height = img_height if img_height >= 200
end
如无需原图比例
#img = File.expand_path("#{Rails.root}/#{product.local_path}"
sheet.add_row [
'',
""
"",
"",
.....
], :height => height, :style => header
// :hyperlink => 图片网络地址 传入此参数 可点击打开图片
if img
sheet.add_image(:image_src => img.base_filename, :start_at => [0, idx+1], :width => 200, :height => img_height, :noMove => false, :noSelect => false)
//如需填满整个单元格 则使用以下方式
#sheet.add_image(:image_src => img, :noSelect => true, :noMove => true) do |image|
# image.start_at 0, idx+1
# image.end_at 1, idx + 2
#end
end
end
sheet.column_widths 30, 20, 15, 25, 15, 15, ... //此处设置单元格宽度, 也可不设置
end
流程大概如此, 水平较低,欢迎诸位大牛指导。