我正在使用Rails中的CarrierWave Gem上传.xls文件。在上传xls文件之前,我想验证.xls文件:
1)包含一定数量的列
2)第一行包含某些标题。
老实说,我甚至不知道从哪里开始。我知道验证必须在模型中发生,我也看到有一个用于验证csv的gem,但对于xls没有。我只需指出正确的方向。
答案 0 :(得分:1)
你可以试试Roo宝石
sheet = Roo::Excel.new("./excel_file.xls")
# Get the header
sheet.row(1)
# Number of columns
sheet.last_column
http://railscasts.com/episodes/396-importing-csv-and-excel
对于验证,只需创建一个可以完成工作的方法:
def validate(sheet)
errors = []
header = sheet.row(1)
num_of_columns = sheet.last_column
errors << 'Need headers' unless (ARRAY_OF_NEEDED_HEADERS - header).empty?
errors << 'Need more columns' if num_of_columns < NUMBER_OF_COLUMNS
errors
end
您可以在模型上创建自己的验证器: http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations