Dynamics 365 For Operations: Pack your data in ZIP folder

  
Hello guys,

Today, I would be sharing the code in D365 FO to pack your data (can be Xml, Excel, Word etc.) in ZIP folder.


using System.IO.Compression;
class SBSCreateZipFile
{       

    /// <summary>
    /// Runs the class with the specified arguments.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
        SBSCreateZipFile file = new SBSCreateZipFile();
        File.createAndDownloadExcelFileViaZip();
    }

    public void createAndDownloadExcelFileViaZip()
    {
        const str extensionZIP = '.zip';
        const str extensionExcel = '.xlsx';

        System.IO.Stream workbookStream = new System.IO.MemoryStream();
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

        using (var package = new OfficeOpenXml.ExcelPackage(memoryStream))
        {
            var worksheets = package.get_Workbook().get_Worksheets();
            var worksheet = worksheets.Add("First sheet");
            var cells = worksheet.get_Cells();
            var cell = cells.get_Item(1,1);
            cell.set_Value("Customer id");

            package.Save();
        }

        memoryStream.Seek(0, System.IO.SeekOrigin::Begin);

        //File::SendFileToUser(memoryStream, "ExcelTesting_Vishal.xlsx"); // TO download only excel i.e. .xlsx

        str formDataFileName = "VishalTiwari_Package";
        str formDataFileNameXML = "ExcelTesting_Vishal";

        System.IO.MemoryStream zipArchiveStream = new System.IO.MemoryStream();
        using (ZipArchive zipArchive = new ZipArchive(zipArchiveStream, ZipArchiveMode::Create, true))
        {
            ZipArchiveEntry dataFileEntry = zipArchive.CreateEntry(formDataFileNameXML + extensionExcel);
            using (System.IO.Stream dataFileEntryStream = dataFileEntry.Open())
            {
                memoryStream.CopyTo(dataFileEntryStream);
            }
                      
        }
        File::SendFileToUser(zipArchiveStream, formDataFileName + extensionZIP);
    }


}

3 comments:

  1. Thanks for a perfect example

    I am quit new in the D365 development in x++, and I am sitting with beneath issue

    What if I have 2 downloads running after each other.

    If your main is followed up by second method that’s
    as well makes a zip file download

    I tried but it seems that it takes the last/second run method unfortunately

    How do I come around that problem?

    Is it possible for you to make example, please ��

    public static void main(Args _args)
    {
    SBSCreateZipFile file = new SBSCreateZipFile();
    File.createAndDownloadExcelFileViaZip();

    File.No2_createAndDownloadExcelFileViaZip();
    }


    ReplyDelete

Powered by Blogger.