4

我制作了一个应用程序,在该应用程序上提供了从 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 %>   
4

1 回答 1

0

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

似乎单元格类型在 Roo 中是一个非常常见的问题,并且几乎没有建议使用 regex 或 char 将其包含在单元格中的解决方法。

我的解决方案会容易得多:

# 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
  • 获取要以不同方式格式化的列的索引
  • 将从浮点数导入的值转换为整数
  • 将整数转换为字符串
于 2016-01-15T14:31:32.513 回答