Category / Section
How to export a SfDataGrid to excel or PDF using ToolBarItems of a Page?
1 min read
SfDataGrid can be exported to excel or PDF by adding ToolbarItems to a ContentPage. You can export the grid using the Activated event of the ToolbarItem.
Refer the below code example in which ToolbarItems are added to export the grid to excel and PDF format.
<ContentPage.ToolbarItems WidthRequest="100" HeightRequest="50"> <ToolbarItem Text="DOWNLOADASEXCEL" Order="Primary" Priority="0" Activated="ExcelExport_Activated"/> <ToolbarItem Text="DOWNLOADASPDF" Order="Primary" Priority="0" Activated="PDFExport_Activated"/> </ContentPage.ToolbarItems>
private void ExcelExport_Activated(object sender, EventArgs e) { isExporting = true; DataGridExcelExportingController excelExport = new DataGridExcelExportingController(); 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(); 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 PDFExport_Activated(object sender, EventArgs e) { isExporting = true; DataGridPdfExportingController pdfExport = new DataGridPdfExportingController(); 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); }
Screenshot
Interface Implementation
You need to implement the below interfaces to save the exported excel and PDF on your devices. The Interface methods are called from the PCL using DependencyService to save the exported excel and PDF.
public interface ISave { void Save(string filename, string contentType, MemoryStream stream); } public interface ISaveWindowsPhone { Task Save(string filename, string contentType, MemoryStream stream); }
Platform Specific Interface Implementation
Android Renderer
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 = System.Environment.GetFolderPath(System.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 Renderer
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); currentController.PresentViewController((UIViewController)qlPreview, true, (Action)null); } }
UWP Renderer
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 export a SfDataGrid to excel or PDF using ToolbarItems of a Page?