Skip to main content

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);
    }


}

Comments