Ruby on rails,阅读和显示csv文件不起作用?
我在Ruby on Rails中实现,我只想要一些容易做的事情,我只想读取一个csv文件,然后在视图中显示输出。 我有一些代码对我来说似乎很好,但我总是得到错误:无法将Tempfile转换为String这是我的控制器:
def match file = params[:file] @original_filename = file.original_filename tmpfile = Tempfile.new("redmine_project_importer") if tmpfile tmpfile.write(file.read) tmpfile.close tmpfilename = File.basename(tmpfile.path) if !$tmpfiles $tmpfiles = Hash.new end $tmpfiles[tmpfilename] = tmpfile else flash[:error] = "Cannot save import file." return end session[:importer_tmpfile] = tmpfilename sample_count = 5 i = 0 @samples = [] FasterCSV.open(file, "r") do |row| @samples[i] = row i += 1 if i > sample_count break end end
我的观点是:
'result'}, {:multipart => true}) do %> sample
谁可以帮助我? 格尔茨
1) FasterCSV.open()
需要一个String文件名,并且你将一个File对象传递给它。
2)如果你想迭代行,它是FasterCSV.foreach(filename)
。 或者FasterCSV.open().each
但在你的情况下,如果你有一个上传的File参数,你最好用
FasterCSV.new(params[:file]).each do |line|
等等
我没有使用FasterCSV,但我认为你应该给Spreadsheet一个看看 – http://spreadsheet.ch/
您应该能够像这样简单地读取csv文件:
book = Spreadsheet.open path_to_file sheet = book.worksheet 0
然后,您可以遍历行并执行您想要的任何操作:
sheet.each do |row| #code end