Ruby-on-rails 将 Excel 导入 Rails 应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2817506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Import Excel into Rails app
提问by Hyman
I am creating a small rails app for personal use and would like to be able to upload excel files to later be validated and added to the database. I had this working previously with csv files, but this has since become impractical.
我正在创建一个供个人使用的小型 Rails 应用程序,并希望能够上传 excel 文件以供以后验证并添加到数据库中。我以前使用 csv 文件进行过此操作,但此后已变得不切实际。
Does anyone know of a tutorial for using the roo or spreadsheet gem to upload the file, display the contents to the user and then add to the database (after validating)? I know this is quite specific, but I want to work through this step by step.
有谁知道使用 roo 或电子表格 gem 上传文件、向用户显示内容然后添加到数据库(验证后)的教程?我知道这是非常具体的,但我想一步一步地完成这个工作。
All I have so far is an 'import' view:
到目前为止,我所拥有的只是一个“导入”视图:
<% form_for :dump, :url=>{:controller=>"students", :action=>"student_import"}, :html => { :multipart => true } do |f| -%>
Select an Excel File :
<%= f.file_field :excel_file -%>
<%= submit_tag 'Submit' -%>
<% end -%>
But have no idea how to access this uploaded file in the controller.
但是不知道如何在控制器中访问这个上传的文件。
Any suggestions/help would be welcomed. Thanks
欢迎任何建议/帮助。谢谢
采纳答案by clyfe
"The Spreadsheet Library is designed to read and write Spreadsheet Documents. As of version 0.6.0, only Microsoft Excel compatible spreadsheets are supported. Spreadsheet is a combination/complete rewrite of the Spreadsheet::Excel Library by Daniel J. Berger and the ParseExcel Library by Hannes Wyss. Spreadsheet can read, write and modify Spreadsheet Documents."
“电子表格库旨在读取和写入电子表格文档。从 0.6.0 版开始,仅支持与 Microsoft Excel 兼容的电子表格。电子表格是 Daniel J. Berger 和 ParseExcel 对电子表格::Excel 库的组合/完全重写Hannes Wyss 的图书馆。电子表格可以读取、写入和修改电子表格文档。”
EDIT
To get the uploaded file you have two options:
1. (recommended) Use something a file upload plugin like paperclipand it will handle the bits and bolts.
2. use the IO object params[:dump][:excel_file]as per: http://guides.rails.info/form_helpers.html#what-gets-uploaded
编辑
要获取上传的文件,您有两个选择:
1.(推荐)使用像回形针这样的文件上传插件,它会处理一些细节。
2. 使用 IO 对象params[:dump][:excel_file]:http: //guides.rails.info/form_helpers.html#what-gets-uploaded
回答by allenwei
回答by cgenco
There's an excellent RailsCast on how to do this with the roogem: http://railscasts.com/episodes/396-importing-csv-and-excel
关于如何使用roogem执行此操作,有一个出色的 RailsCast :http: //railscasts.com/episodes/396-importing-csv-and-excel
回答by jalagrange
Hey I use the spreadsheet gem and wrote a simple app to understand how it all fits together. It currently runs on Rails 3.1 and Carrierwave, hope this helps:
嘿,我使用电子表格 gem 并编写了一个简单的应用程序来了解它们是如何组合在一起的。它目前在 Rails 3.1 和 Carrierwave 上运行,希望这有助于:

