When you want to import a CSV file in NAV you can use XmlPorts / DataPorts, or you can hanlde the import from within a code unit. This article describes the importing of the file using only C/AL code.
Reading the file
First of all you will need some Local variables to handle the import.
The ‘Buffer’ is used to store a complete line an pass it to a function that will handle the line. I use one global variable to keep track of the line number we are handling.
ImportFilePath := ""; InitVars(Rec); ImportFile.OPEN(ImportFilePath); ImportFile.CREATEINSTREAM(ImportStream); WHILE NOT ImportStream.EOS DO BEGIN ImportStream.READTEXT(Buffer); IF (LineCounter > 0) THEN ProcessLine(Buffer, ','); LineCounter += 1; END; ImportFile.CLOSE;
Ok, the code above Opens the file and creates a new InStream. Then we loop the text of the file with the READTEXT function until we are at the end of the file.
After each line the global Line counter is incremented with 1. Because we are using the line counter you can skip the first X records to prevent your code from processing the header line(s).
The processLine function is the one that handles the actual logic for importing the data line per line.
Processing the line
Because there is no ‘split’ function in NAV we need to loop the line and process chunk by chunk. You can do this with the string functions available in navision. The code below looks for the first position of the given delimiter, takes the value and assigns it to a pre declared variable. After the value has been assigned the part of the string is removed from the base string.
ProcessLine(Line : Text;Delimiter : Text) Counter := 1; WHILE STRPOS(Line, Delimiter) > 0 DO BEGIN Value := COPYSTR(Line, 1, STRPOS(Line,Delimiter) -1); CASE Counter OF 1 : MyVar1 := Value; 2 : MyVar2 := Value END; Line := DELSTR(Line,1, STRPOS(Line,Delimiter) ); Counter +=1; END; // Logic to handle the vars go here