我正在尝试使用axlsx在后台生成excel文件并保存(Rails4.2)。在axlsx的GitHub页面中,它显示As of Rails 4.1 you must use render_to_string to render a mail attachment
。但是,它给我一个错误NoMethodError: undefined method 'render_to_string' for #<CreateExcelSheetWorker:0x007fbccf51db30>
我的工人阶级:
class CreateExcelSheetWorker
include Sidekiq::Worker
include Sidetiq::Schedulable
recurrence { daily }
def perform()
model = SomeModel.where(wanted: true).order(started_at: :desc)
xlsx = render_to_string handlers: [:axlsx], formats: [:xlsx], template: "template/file", locals: {model: model}
path = "/tmp/a.xlsx"
File.open(path, "w+") do |f|
f.write(xlsx)
end
end
end
我无法弄清楚如何解决这个问题,感谢任何帮助。
答案 0 :(得分:3)
render_to_string
评论是在动作邮件中使用gem。在任何类型的视图上下文之外,您必须直接使用xlsx builder api。像这样:
package = Axlsx::Package.new do |p|
p.workbook.add_worksheet(name: "Summary") do |sheet|
sheet.add_row ["foo", 1]
end
end
File.write(filename, package.to_stream.read)
答案 1 :(得分:1)
塞尔吉奥的回答很好。但是,如果您想使用axlsx_rails模板,可以使用此示例,它构建一个伪视图上下文来呈现模板:
def userTrigger() {
[$class: 'UsernamePasswordMultiBinding', credentialsId: jenkins_creds, usernameVariable: 'J_USER', passwordVariable: 'J_PASS'],
]){
cmd = "curl -s -u \${J_USER}:\${J_PASS} \${env.BUILD_URL}api/json | python -mjson.tool | grep userId | awk '{print \$2}' | tr -d '"|,' "
def ut = sh(returnStdout: true, script: cmd)
return ut
}
}