3

当我导入 excel 数据文件时,将格式保存为数字。

Excel 示例

|num_doc| |name|
  1234     CR7
  5678     Beckham
  9102     Bush

控制器client_controller.rb

def import
  Client.import(params[:file])
end

模型客户端.rb

@errors = []
spreadsheet = open_spreadsheet(file)
  (2..spreadsheet.last_row).each do |i|
    column1 = spreadsheet.cell(i,'A').to_s  
    column2 = spreadsheet.cell(i,'B').to_s

    client = Client.new(:num_doc => column1,
                        :name => column2)

    if client.save
      # stuff to do on successful save 
    else
      client.errors.full_messages.each do |message|
        @errors << "Issue on line #{i}, <strong>column #{message}</strong>".html_safe
      end
    end
 end  
 @errors #  <- need to return the @errors array   
end  

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Csv.new(file.path, nil, :ignore)
  when ".xls" then Excel.new(file.path, nil, :ignore)
  when ".xlsx" then Excelx.new(file.path, nil, :ignore)
  else raise "Excel issue: #{file.original_filename}"
  end
end

当我导入 excel 文件时,列num_doc正在保存添加数字格式并希望保存字符串值。

|num_doc|   |name|
1234.0      Cr7
5678.0      Beckham

我试过但仍然保存为数字。

 column1 = spreadsheet.cell(i,'A').to_s #to String

 :num_doc => column1.to_s  #to string
4

0 回答 0