Import CSV into CACHÉ
Here's a practical example of how to import data from a CSV file into InterSystems CACHÉ using ObjectScript
Assuming your CSV file is simple (e.g., comma-separated, with headers), you can use %Stream.FileCharacter to read it line by line and parse the data.
ClassMethod ImportCSV(filePath As %String) As %Status {
Set stream = ##class(%Stream.FileCharacter).%New()
Set sc = stream.LinkToFile(filePath)
If 'sc Quit sc
While 'stream.AtEnd {
Set line = stream.ReadLine()
Set fields = $ListFromString(line, ",")
// Example: Save to a persistent class
Set obj = ##class(MyApp.Data).%New()
Set obj.Name = $List(fields,1)
Set obj.Age = $List(fields,2)
Set obj.Email = $List(fields,3)
Do obj.%Save()
}
Quit $$$OK
}Comments
Hi! The complete code example makes it much easier to understand, thank you very much!
Just realised this is an old(ish) post but it has had a recent response so I'll still add the below FWIW...
This is nice an simple but be aware it doesn't handle commas, or other potentially problematic characters, in a string value.
CSV requires that any value containing quotes or the delimiter (comma) should be quoted, anything that reads in CSV should handle this.
Given an example "one,2,three,4" your example works but """one,"",2,three,4" will not, it will create a list with 5 parts.
set line = """one,"",2,three,4"
set fields = $ListFromString(line, ",")
for n = 1:1:$listlength(fields) w !,$list(fields,n)
"one
"
2
three
4The %SQL.Util.Procedures class has some useful CSV methods or take a look at CSVGEN.