2017-03-09

[AX 365] Upload and Read Excel File

This is a sample to upload and read Excel file.

class RunnableClass1UploadExcel
{       
    public static void main(Args _args)
    {       
        FileUploadTemporaryStorageResult result;
        str                 fileUrl;
        System.IO.Stream    stream;

        OfficeOpenXml.ExcelWorksheet    workSheet;
        OfficeOpenXml.ExcelPackage      package;
        OfficeOpenXml.ExcelRange        cells;

        int         rowCount, colCount;
        anytype     anyValue;
        container   conRow;
        ;
        result = File::GetFileFromUser() as FileUploadTemporaryStorageResult;
       
        if (result && result.getUploadStatus())
        {
            fileUrl = result.getDownloadUrl();
            try
            {
                stream = File::UseFileFromURL(fileUrl);
                package = new OfficeOpenXml.ExcelPackage(stream);

                if(package)
                {
                    worksheet   = package.get_Workbook().get_Worksheets().Copy("Sheet1","Data");
                    cells       = worksheet.get_Cells();
                    rowCount    = worksheet.get_Dimension().get_End().get_Row();
                    colCount   = worksheet.get_Dimension().get_End().get_Column();

                    for (int i=2;i<=rowCount;i++)//row
                    {
                        conRow = conNull();
                        for (int j=1;j<=colCount;j++)//column
                        {
                            anyValue= cells.get_Item(i, j).get_Value();
                            conRow += anyValue;
                        }

                        if(conRow)
                        {
                            info(
                                strFmt("%1 - %2",
                                    any2Str(conPeek(conRow, 1)),
                                    any2Str(conPeek(conRow, 2))
                                    )
                                );
                        }
                    }
                }
            }
            catch(Exception::Error)
            {
                info(strFmt("%1 - %2",Exception::Error, fileUrl));
            }
            result.deleteResult();
        }
    }

}