Exporting CSV Files in Dynamics AX

One thing that really comes in handy (more often than you would think) is writing files from X++ code.

There are multiple reasons for doing this: exporting data, writing log files, saving records etc.

For example, I like writing data in CSV files because it’s fast, simple and best of all you can open the file using Excel and you have the format you want.

Let’s say you want a list of  all open sales orders from today.

Here is the code:

static void PCO_CSVFile(Args _args)
	SalesTable              	salesTable;
	System.IO.StreamWriter  	streamWriter;
	FileName                	fileName;
	utcDateTime             	todaysDate;
	TimeOfDay               	midnight;
	str                     	inputLine;
	//setting the date for today at midnight
	midnight = str2time('00:00:00');
	todaysDate = DateTimeUtil::newDateTime(today(), midnight);
	//setting the path and file name
	fileName	= WINAPI::getTempPath() + "TodaysOpenOrders" + ".csv";
	//initializing the streamWriter
	//nice part here is we can choose encoding (come in handy more often than not)
	streamWriter = new System.IO.StreamWriter(fileName, 
	//creating the heading and inserting it in the file
	inputLine = 'SalesID;Customer Account;Payment Mode;Created At';
	while select * from salesTable where salesTable.createdDateTime >= todaysDate
        	&& salesTable.SalesStatus == SalesStatus::Backorder
    	inputLine = strFmt('%1;%2;%3;%4',
    	//inserting a new line every time
	//don't forget to close the file
	info("You are done!");

Of course there are other classes too that you can use to write a CSV file. One example is the CommaTextIo Class. I would recommend using this Class if you are not sure what Encoding you should use.

Hope this helped.