Quantcast
Channel: Microsoft Dynamics 365 Community
Viewing all articles
Browse latest Browse all 10657

Dynamics 365 For Operations: Pack your data in ZIP folder

$
0
0
  
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;
classSBSCreateZipFile
{       

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

    publicvoid createAndDownloadExcelFileViaZip()
    {
        conststr extensionZIP = '.zip';
        conststr 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);
    }


}

Viewing all articles
Browse latest Browse all 10657

Trending Articles