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
流程大概如此, 水平較低,歡迎諸位大牛指導。