所以,这适用于所有面临同样问题或第一次这样做的人。
我使用'caxlsx_rails' 作为我的电子表格生成器。
首先,问题我不知道为什么 Windows 10 中的 Microsoft excel 中没有加载图像。我已经在 google sheet 上进行了测试,但这个解决方案适用于它。
我在 git 上看到了关于此图像未呈现问题的未解决问题。希望它会得到修复。
所以我发布了部分可行的解决方案。
在 GemFile 中
gem 'caxlsx'
gem 'caxlsx_rails'
在控制器中
def export_data
render xlsx: 'export_data', template: 'some_view_path/export_data.xlsx.axlsx',
filename: "data_#{DateTime.now.strftime("%d-%m-%Y")}.xlsx", disposition: 'inline'
end
在视图中,xlsx 的模板
## some_view_path/export_data.xlsx.axlsx
wb = xlsx_package.workbook # create excel book
wb.add_worksheet(name: "Data Sheet Name") do |sheet|
header = wb.styles.add_style({:alignment => {:horizontal => :center, :vertical =>
:center, :wrap_text => true}, :border => { :style => :thin, :color => "000000" }})
border = wb.styles.add_style({:border => { :style => :thin, :color => "000000" }})
align_right = wb.styles.add_style({:alignment => {:horizontal => :right}})
align_left = wb.styles.add_style({:alignment => {:horizontal => :left}})
sheet.add_row
## empty row
sheet.add_row ["Data1", "Data2", "Data3" , "Data4" , "Image"], style: header
Model.all.each do |obj|
row = sheet.add_row [obj.data1, obj.data2, obj.data3, obj.data4], height: 100
index = row.row_index + 1
# this is just to point out where to display image
start_at = "E#{index}"
# image header/column is on E
img = obj.images.first
# if you hae multiple image you can get all and display them accordingly,
# here i am only taking first one, as it satisfies my requirement.
path = ActiveStorage::Blob.service.send(:path_for, img.key)
# getting actual location for activeStorage file,
# if you have image file location, you can point it directly
sheet.add_image(image_src: path, start_at: start_at, width: 100, height: 100)
# adding image
end
end
excel文件下载按钮
在某些方面
<%= link_to "Export Sample", export_sample_your_controller_path(format: :xlsx), class:
"btn btn-smbtn-primary float-right" %>
我希望这会对某些人有所帮助。
问候