【问题标题】:Saving xlsx file in rails在rails中保存xlsx文件
【发布时间】:2020-07-30 16:32:16
【问题描述】:

我一直在尝试在我的应用中生成一个 XLSX 文件。我正在使用 gem 'acts_as_xlsx'。

问题是文档是在后台生成的,我不想渲染视图。这是一个应该返回 XLSX 文件的脚本。

我正在尝试做类似的事情:

file = File.open("report.xlsx", relation.to_xlsx, type: "application/vnd.openxmlformates-officedocument.spreadsheetml.sheet")

这会返回错误,因为 File.open 的第二个参数必须是字符串。

提前致谢!

【问题讨论】:

    标签: ruby-on-rails-4 xlsx axlsx


    【解决方案1】:

    to_xlsx 应该返回 Axlsx 包。该包将自己保存到一个文件中:

    relation.to_xlsx.serialize("report.xlsx")
    

    但是,如果您要通过电子邮件发送它,您只需将其作为附件放置即可。您无需将其保存为文件:

    class UserMailer < ActionMailer::Base
      def export(users)
        content = User.to_xlsx(data: users).to_stream.string
        attachments["Users.xlsx"] = {mime_type: Mime::XLSX, content: content}
        ...
      end
    end
    

    此外,您会在上面注意到,acts_as_xlsx 为您注册了 Mime::XLSX。所以你可以使用它来代替长的 mime 字符串。

    【讨论】:

    • 谢谢。我没有使用任何控制器或邮件程序,而是在脚本中生成文件。它有帮助。谢谢。最后我的代码是:relation_xlsx = relation.to_xlsx;关系_xlsx.serialize("report.xlsx"); serialized_relation = 关系_xlsx.to_stream; file = File.open('report_streamed.xlsx', 'w'); file.write(serialized_relation.read) 需要将 .to_xlsx 和 .serialize 方法分开,因为 serialize 返回 true,所以如果之后尝试:relation_xlsx.to_stream 它将返回“Undefined method to_stream for true:TrueClass
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多