Using X++ code Reading to CSV file

时间:2022-03-12 16:23:29

Using x++ code Reading to CSV file

wrote by Jimmy on DEC 31th 2010 

static void Jimmy_ReadCSVFile(Args _args)
{
    FileIOPermission    fileIOPermission;
    Io                  infile;
    int                 lineNum;
    container           res;
    str                 line;
    filename            name;
    #define.delimiter(",")
    #define.ctrl("\r\n")

    Io OpenFile(str filename, str _Mode, boolean _commaIO = false)
    {
        FileIoPermission perm;
        io               fileIo;
        ;
        perm = new FileIoPermission(filename, _mode);
        perm.assert();

        if (_commaIO)
            fileIo = new commaTextIO(filename, _mode);
        else
            fileIo = new asciiIO(filename, _mode);

        if (!fileIo
            || fileIo.status() != IO_Status::Ok)
        {
            throw error(strfmt("@SYS73665", filename));
        }

        return fileIo;
    }
    ;
    Name = WinAPI::getOpenFileName(infolog.hWnd(),
                                   ["CSV Files",'*.CSV'],
                                   @"c:\...\desktop",
                                   "Open files");
    IF(!Name)
        return;
    try
    {
        infile = OpenFile(Name, 'r', false);
        if(infile)
        {
            infile.inFieldDelimiter(#delimiter);
            infile.inRecordDelimiter(#Ctrl);

            LineNum = 0;
            setprefix(strfmt("Reader File %1",Name));
            while(infile.status() == IO_Status::Ok)
            {
                res = infile.read();
                if(res)
                {
                    LineNum++;
                    info(strfmt("%1,%2,%3,%4", conpeek(res, 1),conpeek(res,2),conpeek(res,3),conpeek(res,4)));
                }
            }
            info(int2str(LineNum));
        }
        else
        {
            error("can't read the file");
        }
        CodeAccessPermission::revertAssert();
    }
    catch
    {
        error("import error");
    }
}