Wednesday, July 15, 2015

X++ Create a simple CSV file

Hello, I found that there are many ways to create a CSV file. Today I will show the simple code which made by textBuffer class.

class GenerateSimpleCSV
{
    //Class
    FileIOPermission    fileIOPermission;

    //Variable
    TextBuffer          textBuffer;
    str                 fileName;

    //Macro
    #File
    #xppTexts
}

---

private void openFile()
{
    fileName = WINAPI::getTempPath() + "test" + #CSV;
    new FileIoPermission(filename, #io_write).assert();
    textBuffer = new TextBuffer();
}

---

private void writeHeader()
{
    textBuffer.appendText('No,');
    textBuffer.appendText('Name,');
    textBuffer.appendText('Surname');

    textBuffer.appendText(#newline);
}

---

private void appendLine()
{
    int     i;
    str     name    = 'aa',
            surname = 'bbb';
    ;

    for (i=1; i<=3; i++)
    {
        textBuffer.appendText(strFmt('"%1",',i));
        textBuffer.appendText(strFmt('"%1",',name));
        textBuffer.appendText(strFmt('"%1"' ,surname));

        textBuffer.appendText(#newline);
    }
}

---

private void closeFile()
{
    textBuffer.toFile(fileName);
    CodeAccessPermission::revertAssert();
}

---

public void execute()
{
    this.openFile();
    this.writeHeader();
    this.appendLine();
    this.closeFile();
}


After finished creating the class, we call it by the below job.

static void testGenSimpleCSV(Args _args)
{
    //Class
    GenerateSimpleCSV   genSimpleCSV;
    ;

    genSimpleCSV = new GenerateSimpleCSV();
    genSimpleCSV.execute();
    info('done!');
}


The result looks like the below picture. Have a nice day!

No comments:

Post a Comment