Wednesday, July 15, 2015

X++ Export an Unicode CSV file

From the previous post. X++ create a simple CSV file.We made a simple CSV, but sometimes we need to export a field as Unicode. For example the japanese font.

We probably get the result file like as below.







We can fix this issue easily by enhance the existing code a bit.
from
private void closeFile()
{
    textBuffer.toFile(fileName);    
    CodeAccessPermission::revertAssert();
}

to
private void closeFile()
{
    textBuffer.toFile(fileName, FileEncoding::UTF8);    
    CodeAccessPermission::revertAssert();
}

The result looks nice eventually.

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!