Loading and saving workbook in WinUI
24 Jul 20264 minutes to read
Prerequisites
- Visual Studio 2022 (17.0 or later) with the .NET Desktop Development workload and the Windows App SDK installed.
- Install the Syncfusion.XlsIO.NET NuGet package in your project.
- Register your Syncfusion® license key in your project. Refer to the licensing overview for details.
NOTE
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add the
Syncfusion.Licensingassembly reference and include a license key in your projects. Please refer to this link to know about registering the Syncfusion® license key in your applications to use our components.
Opening an existing workbook from stream
You can open an existing workbook from a stream by using the overloads of the Open methods of the IWorkbooks interface.
// Create a new instance of ExcelEngine
using (ExcelEngine excelEngine = new ExcelEngine())
{
// Initialize IApplication
IApplication application = excelEngine.Excel;
// Load the embedded resource into a stream
Assembly executingAssembly = typeof(App).GetTypeInfo().Assembly;
using (Stream inputStream = executingAssembly.GetManifestResourceStream("WinUISample.Sample.xlsx"))
{
// Open the workbook through the Open method of IWorkbooks
IWorkbook workbook = application.Workbooks.Open(inputStream);
}
}Saving an Excel workbook to stream
You can save the created or manipulated workbook to a stream using the SaveAs methods.
// Create a new instance of ExcelEngine
using (ExcelEngine excelEngine = new ExcelEngine())
{
// Initialize IApplication
IApplication application = excelEngine.Excel;
// Load the embedded resource into a stream
Assembly executingAssembly = typeof(App).GetTypeInfo().Assembly;
using (Stream inputStream = executingAssembly.GetManifestResourceStream("WinUISample.Sample.xlsx"))
{
// Open the workbook
IWorkbook workbook = application.Workbooks.Open(inputStream);
// To-Do: some manipulation
// Set the version of the workbook
workbook.Version = ExcelVersion.Xlsx;
// Save the workbook to a memory stream
using (MemoryStream outputStream = new MemoryStream())
{
workbook.SaveAs(outputStream);
outputStream.Position = 0;
// Save the memory stream to a user-chosen file via FileSavePicker
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
savePicker.SuggestedFileName = "Output";
savePicker.FileTypeChoices.Add("Excel Files", new List<string>() { ".xlsx" });
StorageFile storageFile = await savePicker.PickSaveFileAsync();
using (Stream fileStream = await storageFile.OpenStreamForWriteAsync())
{
await outputStream.CopyToAsync(fileStream);
}
}
}
}