gpt4 book ai didi

excel - 在 Rails 中将 Excel 单元格从数字格式化为文本

转载 作者:行者123 更新时间:2023-12-02 12:13:51 25 4
gpt4 key购买 nike

我制作了一个应用程序,提供从 CSV 和 Excel 文件导入记录的功能。我正在使用 roo gem。记录添加成功,但问题是在从 Excel 导入记录时,它会向每个数字字段添加 .0。我不想要它,因为我有一些字段,如注册号、卷号、联系号,它会在每个字段中添加 .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

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 导入使导入变得更容易。

看来细胞类型很漂亮common problem in Roo并且几乎没有建议使用正则表达式或字符包含在您的单元格中的解决方法。

我的解决方案会更容易:

# 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
  • 获取您想要以不同方式设置格式的列的索引
  • 将导入的值从浮点转换为整数
  • 将整数转换为字符串

关于excel - 在 Rails 中将 Excel 单元格从数字格式化为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31302189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com