How to customize cell value while exporting the Xamarin.iOS DataGrid into Excel and PDF?
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
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
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
Conclusion
I hope you enjoyed learning about how to customize cell value while exporting the Xamarin.Forms DataGrid into Excel and PDF.
You can refer to our Xamarin.iOS DataGrid feature tour page to know about its other groundbreaking feature representations. You can also explore our Xamarin.iOS DataGrid documentation to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!