PeopleCode | Creating a comma-separate value (CSV) file
A. CSV Obsession
Users generally love having CSV files at their disposal. They can open the files in Excel and play around with the data to their heart’s content. Better still for the developer, they are easy to create in PeopleCode. You do not need to concern yourself with native Microsoft Excel files or whatever other application the user happens to be using. I’ve yet to encounter any analytical software that fails to read plain text CSV files.
As developers, CSV files are also useful for troubleshooting purposes. If you want to quickly create your own custom trace file, a quick-and-dirty CSV file is always an option.
In this post, we will consider two approaches for creating simple CSV files in PeopleCode.
B. Using a File Layout for a CSV
Firstly, here’s an example of a CSV being created via a file layout (the file layout must be defined as type ‘CSV’):
/* Declare varaibles */ Global File &CSVFile, &fileLog; Local Rowset &fileRS; /* Define CSV file and write column headings */ &CSVFile = GetFile("file_name.csv", "w", "a", %FilePath_Relative); &CSVFile.WriteLine("Column 1,Column 2,Column 3,Column 4"); /* Set the file layout for the CSV file */ &CSVFile.SetFileLayout(FileLayout.FILE_LAYOUT_NAME); /* Populate the rowset for the file layout */ &fileRS = &CSVFile.CreateRowset(); &fileRS.Fill("where EMPLID = :1", ¤tEmplid); /* Write the rowset to file and close the file */ &CSVFile.WriteRowset(&fileRS, True); &CSVFile.Close();
C. Using a Direct Write for a CSV
Secondly, here’s an example of a CSV being created directly, without the use of a file layout:
Local integer &i; Local string &CSVLine; Local Record &acadCareerRec; Local Rowset &acadCareerRS; Local File &CSVFile; /* Define CSV file and write column headings */ &CSVFile = GetFile("file_name.csv", "w", "a", %FilePath_Relative); &CSVFile.WriteLine("Column 1,Column 2,Column 3,Column 4"); /* Define rowset and fill with values */ &acadCareerRS = CreateRowset(Record.ACAD_CAR_TBL); &acadCareerRS.Fill(); /* Loop through each row of the rowset */ for &i = 1 to &acadCareerRS.ActiveRowCount &acadCareerRec = &acadCareerRS.GetRow(&i).ACAD_CAR_TBL; /* Write the current details to file */ &CSVLine = &acadCareerRec.INSTITUTION.Value | "," | &acadCareerRec.ACAD_CAREER.Value | "," | &acadCareerRec.DESCR.Value; &CSVFile.Writeline(&CSVLine); end-for; /* Close the CSV File */ &CSVFile.Close();
See Also:
Tip 011: Determine Current Working Directory
Tip 014: Creating a Custom Log File
Tip 036: Introduction to File Layouts
Tip 045: Introduction to Tracing