[英]Header not in Row 1 CSV Import Ruby Rails
我正在嘗試導入CSV文件,並且標題行一直在移動,有時在20行中,有時在25行中,依此類推,但是字段“ SPIRIT Barcode”始終位於標題中,這是我唯一的選擇我對此感興趣。 我將其保存在“條形碼”中。
我該如何操作才能找到“ SPIRIT Barcode”行並將其用作標題? (標題上方的所有內容都可以忽略)
def self.import(file)
@b = []
CSV.foreach(file.path, headers: true) do |row|
entry = ZygReport.find_by(barcode: row['SPIRIT Barcode']) || new
entry.update({
:barcode => row['SPIRIT Barcode'],
})
entry.save!
@b << [entry.barcode]
end
end
忽略@b
,這是另一個函數。
此代碼僅解析一次文件,逐行讀取並查找SPIRIT Barcode
。
找到該行后,它將刪除換行符,並將其拆分以獲取標頭名稱數組。
CSV.parse
可以直接在文件上調用。 由於已經讀取到標題為止,因此它將從正確的行開始:
require 'csv'
sep = ';'
File.open('test.csv'){|file|
header = file.find{|line| line.include?('SPIRIT Barcode')}.chomp.split(sep)
CSV.parse(file, headers: header, col_sep: sep).each do |row|
p row
end
}
使用test.csv
作為:
Ignore me
Ignore me
SPIRIT Barcode; B; C
1; 2; 3
4; 5; 6
輸出:
#<CSV::Row "SPIRIT Barcode":"1" " B":" 2" " C":" 3">
#<CSV::Row "SPIRIT Barcode":"4" " B":" 5" " C":" 6">
使其適應您的數據應該不難。
這未經測試,但這是您要執行的操作的一般思路:
require 'csv'
header_found = false
File.foreach('path/to/file.csv') do |li|
next unless header_found || li['SPIRIT Barcode']
header_found = true
# start processing CSV...
CSV.parse(li) do |row|
# use row here...
end
end
如果要跟蹤值,則必須弄清楚找到標題后的處理方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.