ruby 导出excel图片

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

流程大概如此, 水平较低,欢迎诸位大牛指导。

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值