Generate and download a csv file using X++
Within Dynamics 365 HQ we often need to be able to export data as a csv file. This article explains how we can generate a csv file.
The following lines of code can be used to create and download a csv file
Create a writable stream.
CommaStreamIo streamIO = CommaStreamIo::constructForWrite();
streamIO.writeExp('Id', 'Title'); // These will represent the header of the csv file
streamIO.writeExp('001', 'Science'); // Row 1
streamIO.writeExp('002', 'Nature'); // Row 2
// Get the stream
System.IO.Stream stream = streamIO.getStream();
const str extensionCsv = '.csv';
stream.Position = 0;
// StreamReader to read as str
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
str csvFileContent = reader.ReadToEnd();
// This line will allow the file to be auto downloaded via the browser on the client machine
File::SendStringAsFileToUser(csvFileContent, 'file' + extensionCsv);
Comments
Post a Comment