Axlsx导轨.生成.xlsx文件并将文件名响应为json/html [英] Axlsx Rails. Generate .xlsx file and respond filename as json/html

查看:192
本文介绍了Axlsx导轨.生成.xlsx文件并将文件名响应为json/html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用axlsx_rails gem生成xlsx文件.

I am generating xlsx files with axlsx_rails gem.

收集用户输入后,我将数据发布到/basic_report_post.xlsx

After collecting user input I am posting data to /basic_report_post.xlsx

控制器动作类似于

def basic_report_post
    @config = params[:config]
    @data = params[:data]
    @filename = "#{Rails.root}/public/test.xlsx"

    respond_to do |format|
      format.xlsx {
        render xlsx: 'basic_report_post'
      }
    end
  end

查看此操作的文件basic_report_post.xlsx.axlsx

View file for this action basic_report_post.xlsx.axlsx

wb = xlsx_package.workbook    
wb.add_worksheet(name: 'Data1') do |s|    
# Drawing columns    
end
xlsx_package.serialize @filename

我的问题是,我正在获取原始.xlsx文件的响应数据(在成功后操作中). 但是我需要以某种方式响应@filename(格式为json/html),然后再下载.

My problem is that I am getting response data(in post success action) that is raw .xlsx file. But I need somehow respond @filename (format json/html) to download it after.

推荐答案

可以使用axlsx_rails模板渲染器创建字符串并将其保存到文件:

It is possible to use the axlsx_rails template renderer to create a string and save it to file:

def basic_report_post
  @config = params[:config]
  @data = params[:data]
  @filename = "#{Rails.root}/public/test.xlsx"
  File.open(@filename, 'w') do |f|
    f.write render_to_string(handlers: [:axlsx], formats: [:xlsx], template: 'path/to/template')
  end
  render json: {name: @filename}
end

然后,如果需要,您可以使用模板直接提供文件.

Then you can use the template to serve the file directly if need be.

这篇关于Axlsx导轨.生成.xlsx文件并将文件名响应为json/html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆