We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to customize cell value while exporting the SfDataGrid into Excel and PDF?

Platform: Xamarin.Android |
Control: SfDataGrid

We can customize a particular cell value while exporting the SfDataGrid to Excel and PDF by handling DataGridPdfExportingController.CellExporting event.

Export to PDF

The below code helps to customize a cell value while exporting the SfDataGrid to PDF. DependencyService.Get<ISave>() and DependencyService.Get<ISaveWindowsPhone> are interfaces that help you to save the exported grid in various platform projects.

private void ExportToPDF_Clicked(object sender, EventArgs e)
{
    isExporting = true;
    DataGridPdfExportingController pdfExport = new DataGridPdfExportingController();
    pdfExport.CellExporting += PdfExport_CellExporting;
    MemoryStream stream = new MemoryStream();
    var doc = pdfExport.ExportToPdf(this.dataGrid, new DataGridPdfExportOption()
    {
        FitAllColumnsInOnePage = true
    });
    doc.Save(stream);
    doc.Close(true);
    if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
        Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("DataGrid.pdf", "application/pdf", stream);
    else
        Xamarin.Forms.DependencyService.Get<ISave>().Save("DataGrid.pdf", "application/pdf", stream);
}
private void PdfExport_CellExporting(object sender, DataGridCellPdfExportingEventArgs e)
{
    if (e.CellValue is int && (int)e.CellValue == 10001)
    {
        e.CellValue = 99999;
    }
}

 

Screenshot

customize cell while Export SfDataGrid to PDF

 

Export to Excel

The below code helps to customize a cell value while exporting the SfDataGrid to Excel. Like PDF exporting, we should add the interfaces implementation for excel exporting also.

private void ExportToExcel_Clicked(object sender, EventArgs e)
{
    isExporting = true;
    DataGridExcelExportingController excelExport = new DataGridExcelExportingController();
    excelExport.CellExporting += ExcelExport_CellExporting;
    DataGridExcelExportingOption exportOption = new DataGridExcelExportingOption();
    if (Device.OS == TargetPlatform.iOS)
    {
        exportOption.ExportColumnWidth = false;
        exportOption.DefaultColumnWidth = 150;
    }
    var excelEngine = excelExport.ExportToExcel(this.dataGrid, exportOption);
    var workbook = excelEngine.Excel.Workbooks[0];
    MemoryStream stream = new MemoryStream();
    workbook.SaveAs(stream);
    workbook.Close();
    excelEngine.Dispose();
 
    if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
        Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("DataGrid.xlsx", "application/msexcel", stream);
    else
        Xamarin.Forms.DependencyService.Get<ISave>().Save("DataGrid.xlsx", "application/msexcel", stream);
}
private void ExcelExport_CellExporting(object sender, DataGridCellExcelExportingEventArgs e)
{
    if (e.CellValue is int && (int)e.CellValue == 10001)
    {
        e.CellValue = 99999;
    }
}

 

Screenshot

 

Customize cell while export SfDataGrid to Excel

 

Interfaces Implementation

public interface ISave
{
    void Save(string filename, string contentType, MemoryStream stream);
}
public interface ISaveWindowsPhone
{
    Task Save(string filename, string contentType, MemoryStream stream);
}
public interface IAndroidVersionDependencyService
{
    int GetAndroidVersion();
}

 

Platform Specific Interface Implementation

Android

public class SaveAndroid : ISave
{
    public void Save(string fileName, String contentType, MemoryStream stream)
    {
        string exception = string.Empty;
        string root = null;
        if (Android.OS.Environment.IsExternalStorageEmulated)
        {
            root = Android.OS.Environment.ExternalStorageDirectory.ToString();
        }
        else
            root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
 
        Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
        myDir.Mkdir();
 
        Java.IO.File file = new Java.IO.File(myDir, fileName);
 
        if (file.Exists()) file.Delete();
 
        try
        {
            FileOutputStream outs = new FileOutputStream(file);
            outs.Write(stream.ToArray());
 
            outs.Flush();
            outs.Close();
        }
        catch (Exception e)
        {
            exception = e.ToString();
        }
        if (file.Exists() && contentType != "application/html")
        {
            Android.Net.Uri path = Android.Net.Uri.FromFile(file);
            string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
            string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            Intent intent = new Intent(Intent.ActionView);
            intent.SetDataAndType(path, mimeType);
            Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
        }
    }
}

 

IOS

public class SaveIOS : ISave
{
    void ISave.Save(string filename, string contentType, MemoryStream stream)
    {
        string exception = string.Empty;
        string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        string filePath = Path.Combine(path, filename);
        try
        {
            FileStream fileStream = File.Open(filePath, FileMode.Create);
            stream.Position = 0;
            stream.CopyTo(fileStream);
            fileStream.Flush();
            fileStream.Close();
        }
        catch (Exception e)
        {
            exception = e.ToString();
        }
        if (contentType == "application/html" || exception != string.Empty)
            return;
        UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController;
        while (currentController.PresentedViewController != null)
            currentController = currentController.PresentedViewController;
        UIView currentView = currentController.View;
 
        QLPreviewController qlPreview = new QLPreviewController();
        QLPreviewItem item = new QLPreviewItemBundle(filename, filePath);
        qlPreview.DataSource = new PreviewControllerDS(item);
 
        //UIViewController uiView = currentView as UIViewController;
 
        currentController.PresentViewController((UIViewController)qlPreview, true, (Action)null);
    }
}

 

UWP

public class SaveWindows : ISaveWindowsPhone
{
    public async Task Save(string filename, string contentType, MemoryStream stream)
    {
        if (Device.Idiom != TargetIdiom.Desktop)
        {
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile outFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            using (Stream outStream = await outFile.OpenStreamForWriteAsync())
            {
                outStream.Write(stream.ToArray(), 0, (int)stream.Length);
            }
            if (contentType != "application/html")
                await Windows.System.Launcher.LaunchFileAsync(outFile);
        }
        else
        {
            StorageFile storageFile = null;
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
            savePicker.SuggestedFileName = filename;
            switch (contentType)
            {
                case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                    savePicker.FileTypeChoices.Add("PowerPoint Presentation", new List<string>() { ".pptx", });
                    break;
 
                case "application/msexcel":
                    savePicker.FileTypeChoices.Add("Excel Files", new List<string>() { ".xlsx", });
                    break;
 
                case "application/msword":
                    savePicker.FileTypeChoices.Add("Word Document", new List<string>() { ".docx" });
                    break;
 
                case "application/pdf":
                    savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string>() { ".pdf" });
                    break;
                case "application/html":
                    savePicker.FileTypeChoices.Add("HTML Files", new List<string>() { ".html" });
                    break;
            }
            storageFile = await savePicker.PickSaveFileAsync();
 
            using (Stream outStream = await storageFile.OpenStreamForWriteAsync())
            {
                outStream.Write(stream.ToArray(), 0, (int)stream.Length);
                outStream.Flush();
                outStream.Dispose();
            }
            stream.Flush();
            stream.Dispose();
            await Windows.System.Launcher.LaunchFileAsync(storageFile);
        }
    }
}

 

Sample Link

How to customizing the cell value while exporting the SfDatagrid to PDF and Excel

 

2X faster development

The ultimate Xamarin UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile