Làm cách nào để sử dụng dữ liệu trong loại tệp CSV này? Hoặc làm thế nào tôi có thể in ví dụ giá trị hàng 2 cho cột "bên trong" và gán nó cho một thuộc tính/thực thể?nhanh chóng 3.1 cách lấy mảng hoặc từ điển từ CSV
Tôi có loại tệp này tôi nhận được từ tệp excel được chuyển thành Số, tôi muốn lấy dữ liệu cho từng cột và sử dụng chúng.
Các tập tin CSV gốc mở với số lượng:
Giao diện điều khiển đầu ra tôi nhận:
Sử dụng phương pháp này:
func readDataFromCSV(fileName:String, fileType: String)-> String!{
guard let filepath = Bundle.main.path(forResource: fileName, ofType: fileType)
else {
return nil
}
do {
var contents = try String(contentsOfFile: filepath, encoding: .utf8)
contents = cleanRows(file: contents)
return contents
} catch {
print("File Read Error for file \(filepath)")
return nil
}
}
func cleanRows(file:String)->String{
var cleanFile = file
cleanFile = cleanFile.replacingOccurrences(of: "\r", with: "\n")
cleanFile = cleanFile.replacingOccurrences(of: "\n\n", with: "\n")
// cleanFile = cleanFile.replacingOccurrences(of: ";;", with: "")
// cleanFile = cleanFile.replacingOccurrences(of: ";\n", with: "")
return cleanFile
}
SOLUTION nhờ Jens Meder
sử dụng
func csv(data: String) -> [[String]] {
var result: [[String]] = []
let rows = data.components(separatedBy: "\n")
for row in rows {
let columns = row.components(separatedBy: ";")
result.append(columns)
}
return result
}
trong viewDidLoad
var data = readDataFromCSV(fileName: kCSVFileName, fileType: kCSVFileExtension)
data = cleanRows(file: data!)
let csvRows = csv(data: data!)
print(csvRows[1][1]) // UXM n. 166/167
vấn đề là gì? Có vẻ như bạn đã đọc dữ liệu. – matt
vâng tôi đọc nó, nhưng tôi chỉ nhận được một chuỗi dài, Làm thế nào tôi có thể in ví dụ giá trị hàng 2 cho cột "bên trong" và gán nó cho một thuộc tính/thực thể? – biggreentree
Bạn đã thử tìm kiếm Stack Overflow chưa? Bạn có thực sự tưởng tượng bạn là người đầu tiên muốn tách một tệp CSV thành các thành phần không? – matt