通过Spreadsheet gem直接下载xls文件,而不将其写入目录
我正在使用这个 Spreadsheet gem 导出 xls 文件。
我的控制器中有以下代码:
def export
@data = Data.all
book = Spreadsheet::Workbook.new
sheet = book.create_worksheet :name => "data"
contruct_body(sheet, @data)
book.write "data.xls"
end
这样,我可以填写数据并将其保存在根目录中。
但我想下载它而不是保存它。如何修改代码以便提示用户选择本地目录来保存文件? (如果不在服务器端保存副本更好)
请帮忙!
I am using this Spreadsheet gem to export xls file.
I have the following codes in my controller:
def export
@data = Data.all
book = Spreadsheet::Workbook.new
sheet = book.create_worksheet :name => "data"
contruct_body(sheet, @data)
book.write "data.xls"
end
In this way, I can fill in the data and save it in the root directory.
But I want to download it instead of save it. How could I modify the code so that the user prompted to select his local directory to save the file? (better if without saving a copy in the server side)
Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将其发送到浏览器而不将其保存为本地文件,如下所示
You can send it to the browser without saving it as a local file at all as follows
您可以尝试此代码
传递
:stream =>; false
到send_file
将指示 Rails 在流式传输之前将整个文件复制到内存中,因此在send_file
之后立即使用File.delete
会没问题,因为send_file
会立即返回,而无需等待下载完成。话虽如此,对于非常大的文件,您可能会看到一些内存瓶颈,具体取决于可用内存量。华泰
You could try this code
Passing
:stream => false
tosend_file
will instruct Rails to copy the entire file into memory before streaming, so usingFile.delete
immediately aftersend_file
would be fine sincesend_file
returns immediately without waiting for the download to complete. Having said that, with very large files you may see some memory bottle necks depending on the amount of memory available.HTH
我知道这太旧了,但我一直在寻找它,所以其他人可能也是如此。
这就是答案。 (我使用的是 Sinatra。)
https://github.com/zdavatz/电子表格/问题/125#issuecomment-370157753
I understand this is insanely old, but I was looking for it so someone else might be.
This is the answer. (I'm using Sinatra.)
https://github.com/zdavatz/spreadsheet/issues/125#issuecomment-370157753
这个案子就发生在我身上。
我使用remote::true的ajax请求导出excel文件,浏览器上没有任何显示,控制台上没有任何错误消息。
从表单中删除远程参数,效果很好。
The case happen on mybody.
I used the ajax request by remote::true to export excel file, nothing display on browser without any error message on console.
Delete the remote params from the form, it works well.