How to retrieve and save the images from an Excel document in Xamarin.Android Excel library?
Syncfusion® Excel (XlsIO) library is a .NET Excel library used to create, read, and edit Excel documents. It also, converts Excel documents to PDF files.
This sample explains how to retrieve and save the image from an Excel document, in Xamarin Android platform.
Steps to retrieve and save the image from an Excel document in Xamarin:
Step 1: Create a new C# Xamarin.Forms application project.


Step 2: Select the template and required platforms to deploy the application.

Step 3: Install the Syncfusion.Xamarin.XlsIO NuGet package as a reference to the .NET Standard project in your Xamarin application from NuGet.org.

Step 4: Add a new Forms XAML page in the portable project, if there is no XAML page defined in the App class. Otherwise, proceed to the Step 5.
- To add the new XAML page, right-click on the project and select Add -> New Item. Add a forms XAML page from the list and name it MainPage.
- In the App class of the portable project (App.xaml.cs), replace the existing constructor of App class with the following code to invoke the MainPage.
C#
public App()
{
InitializeComponent();
MainPage = new MainPage();
}
Step 5: In the MainPage.xaml, add a new button as shown below.
XML
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:CreateExcel" x:Class="CreateExcel.MainPage"> <StackLayout> <!-- Place new controls here --> <Label Text="Welcome to Xamarin.Forms!" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" /> <Button Text="Create Excel" Clicked="OnButtonClicked" HorizontalOptions="Center"/> </StackLayout> </ContentPage>
Step 6: Include the following namespaces in MainPage.xaml.cs file.
C#
using Syncfusion.XlsIO; using System.Reflection; using System.IO;
Step 7: Have a click event for the button in MainPage.xaml.cs file.
C#
void OnButtonClicked(object sender, EventArgs args)
{
}
Step 8: Include the following code snippet in the click event of the button, to retrieve and save an image from an Excel file.
C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
Assembly assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream fileStream = assembly.GetManifestResourceStream("RetrieveAndSave.Sample.xlsx");
IWorkbook workbook = application.Workbooks.Open(fileStream, ExcelOpenType.Automatic);
IWorksheet sheet = workbook.Worksheets[0];
IPictureShape picture = sheet.Pictures[0];
Syncfusion.Drawing.Image image = picture.Picture;
byte[] byteArray = image.ImageData;
MemoryStream stream = new MemoryStream(byteArray);
stream.Position = 0;
//Save the document as file and view the saved document
Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("Image.png", "application/image", stream);
}
Step 9: The SaveAndView method under ISave interface is used to save the stream as file and invoke it for viewing. Click here to download these helper files and add them into mentioned project.
Project | Helper class | Summary |
Portable project | ISave.cs | Base interface for save operation |
Android project | SaveAndroid.cs | Save implementation for Android device |
iOS project | SaveIOS.cs | Save implementation for iOS device |
PreviewControllerDS.cs | Helper file for viewing the Excel file in iOS device | |
UWP project | SaveWindows.cs | Save implementation for UWP device |
WinPhone project | SaveWinPhone.cs | Save implementation for Windows Phone device |
Windows(8.1) project | SaveWindows81.cs | Save implementation for WinRT device |
You can also find the code for SaveAndriod class below.
C#
public async Task SaveAndView(string fileName, String contentType, MemoryStream stream)
{
string root = null;
if (ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Forms.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
}
// Get the root path in android device.
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
else
root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Create directory and file
Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
myDir.Mkdir();
Java.IO.File file = new Java.IO.File(myDir, fileName);
// Remove if the file exists
// if (file.Exists()) file.Delete();
// Write the stream into the file
FileOutputStream outs = new FileOutputStream(file);
outs.Write(stream.ToArray());
outs.Flush();
outs.Close();
// Invoke the created file for viewing
if (file.Exists())
{
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.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
Android.Net.Uri path = FileProvider.GetUriForFile(Forms.Context, Android.App.Application.Context.PackageName + ".provider", file);
intent.SetDataAndType(path, mimeType);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
}
}
Introduced a new runtime permission model for the Android SDK version 23 and above. So, include the following code for enabling the Android file provider to save and view the generated document.
- Create a new XML file with the name of provider_path.xml under the Android project Resources folder and add the following code in it. Eg: Resources/xml/provider_path.xml
<?xml version="1.0" encoding="UTF-8" ?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths>
- Add the following code to the AndroidManifest.xml file located under Properties/AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.InsertImage">
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27" />
<application android:label="RetrieveAndSave.Android">
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>
</manifest>
A complete working sample to retrieve and save image from an Excel file in Xamarin.Forms application using Syncfusion® Excel (XlsIO) library can be downloaded from RetrieveAndSave.zip.
Take a moment to peruse the documentation, where you can find basic worksheet data manipulation options along with features like Conditional Formatting, worksheet calculations through Formulas, adding Charts in worksheet or workbook, organizing and analyzing data through Tables and Pivot Tables, appending multiple records to worksheet using Template Markers, and most importantly PDF and Image conversions etc. with code examples.
Click here to explore the rich set of Syncfusion® Excel (XlsIO) library features.
Note:
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from a trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without a trial message.
Conclusion
I hope you enjoyed learning about How to retrieve and save the images from an Excel document in Xamarin.Android Excel library.
You can refer to our XIsIO’s feature tour page to learn about its other groundbreaking features. Explore our UG documentation and online demos to understand how to manipulate data in Excel documents.
If you are an existing user, you can access our latest components from the License and Downloads page. For new users, you can try our 30-day free trial to check out XlsIO and other Syncfusion® components.
If you have any queries or require clarification, please let us know in the comments below or contact us through our support forums, Support Tickets, or feedback portal. We are always happy to assist you!