格式化Excel中的单元格从数字到文本的轨道

我已经提出了一个应用程序,我已经提供了从CSV和Excel文件导入logging的function。 我正在使用roo gem。 logging添加成功,但问题是在从Excel导入logging的时候,它增加.0到每个字段是数字。 我不想要它,因为我有一些像enrollmen_no,roll_no,contact_no这样的字段,它会在每个23到23.0的字段中加上.0。 我已经把这些提交到数据库varchar现在我想格式的数字文本的Excel单元格。 这将解决我的问题。 告诉我如何格式化Excel单元格从数字到string使用轨道。

这是我的导入文件的代码:

student.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 

students_controller.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 

new.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 %> 

我在我的应用程序中做类似的事情,但通过只从CSV导入导入更容易。

看来, 单元格types是在Roo中相当常见的问题,并没有几个解决方法build议使用正则expression式或字符包括在您的单元格。

我的解决scheme会容易得多:

 # student.rb COLUMNS_TO_STRING = ["organization_id", "enrollment_no", "contact_no"] # and so on 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] row = clean_for row, COLUMNS_TO_STRING 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.clean_for row_as_hash, string_columns_array row_as_hash.each do |key, value| if string_columns_array.include?key row_as_hash[key] = value.to_i.to_s end 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 
  • 得到你想格式不同的列的索引
  • 将从float导入的值转换为整数
  • 将整数转换为string