我制作了一个应用程序,在该应用程序上提供了从 CSV 和 Excel 文件导入记录的功能。我正在使用 roo gem。记录添加成功,但问题是在从 excel 导入记录时,它将 .0 添加到每个数字字段。我不想要它,因为我有一些像enrollment_no、roll_no、contact_no 这样的字段,它会将.0 添加到每个字段中,就像它从23 到23.0 一样。我已经将这些文件转换为数据库中的 varchar,现在我想将 excel 单元格从数字格式化为文本。它将解决我的问题。告诉我如何使用rails将excel单元格从数字格式化为字符串。
这是我导入文件的代码:
学生.rb:
def self.import(file, current_organization_id)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
record = Student.find_by(:organization_id => current_organization_id,:enrollment_no => row["enrollment_no"]) || new
record.organization_id= current_organization_id
record.attributes = row.to_hash.slice(*row.to_hash.keys)
record.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::CSV.new(file.path)
when ".xls" then Roo::Excel.new(file.path)
when ".xlsx" then Roo::Excelx.new(file.path)
else raise "Unknown file type: #{file.original_filename}"
end
end
学生控制器.rb:
def import
Student.import(params[:file], session[:current_organization_id])
#puts @session[:current_organization_id].inspect
redirect_to students_path, notice: "Record imported Successfully."
end
新的.html.erb:
<%= form_tag import_students_path, multipart: true do %>
<%= file_field_tag :file , :required=> true%> <br/>
<%= submit_tag "Import" , :class => "btn btn-primary btn-block" %>
<% end %>