在 Rails 中下载工作簿而不将其保存到磁盘 ruby​​xl

Downloading workbook without saving it to disk rubyxl in Rails

Rails 4.2
RubyXL

我正在使用 RubyXL 创建工作簿。我可以将其写入磁盘:

workbook.write("path/to/desired/Excel/file.xlsx")

然后像这样下载:

send_file(workbook.write("path/to/desired/Excel/file.xlsx"), options = {:filename => 'myworkbook.xlsx', :disposition => 'attachment'})

关于如何下载它而无需先将其保存到服务器的任何建议?

您可以将工作簿直接转换为字符串:

def get_worksheet_as_string
  workbook = RubyXL::Workbook.new
  # Fill workbook here or leave as is to download empty
  send_data workbook.stream.string, filename: "myworkbook.xlsx",
                                    disposition: 'attachment'
end

如果您在 Sinatra 工作:

get '/download-xlsx/?' do
    content_type 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    attachment(filename = "filename.xlsx", disposition = :attachment)

    workbook = RubyXL::Workbook.new

    # Fill the workbook with data

    workbook.stream
end

认为它可能对在 Sinatra 工作的人有所帮助!