Articles in this section
Category / Section

How to mail merge Word document in Xamarin.Android?

3 mins read

Mail merge is a process of merging data from a data source to a Word template document. Syncfusion Essential DocIO is a Xamarin Word library used to generate reports like invoice, payroll, etc., by performing mail merge faster in a batch process without Microsoft Word or interop dependencies. Using this library, you can mail merge Word document in Xamarin.Android.

Steps to Mail merge Word document programmatically:

  1. Create a new C# Xamarin Android application project. Create Xamarin.Android application in Visual Studio
  2. Select a project template and minimum android version for the application. Create new Blank Android app
  3. Install Syncfusion.Xamarin.DocIO NuGet package as a reference to the .NET Standard project in your Xamarin application from NuGet.org. Add DocIO NuGet package reference to the project
  4. In Main.xaml add the new button and define the click event to generate the Word file.

i)In Main.xaml page add the following code to add the button

XAML

<Button
   android:id="@+id/MyButton"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
/>

ii)In MainActivity.cs file add the following code to define the click event to generate Word file.

C#

protected override void OnCreate(Bundle savedInstanceState)
{
  base.OnCreate(savedInstanceState);
  // Set our view from the "main" layout resource
  SetContentView(Resource.Layout.activity_main);
  Button button = FindViewById<Button>(Resource.Id.MyButton);
  button.Text = "Create Word";
  button.Click += OnButtonClicked;
}
  1. Include the following namespace in the MainActivity.cs file.

C#

using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System.Reflection;
  1. In the click event method (OnButtonClicked) add the following code to mail merge Word document and save it in a stream.

C#

async void OnButtonClicked(object sender, EventArgs e)
{
    //"MainActivity" is the class of Portable project.
    Assembly assembly = typeof(MainActivity).GetTypeInfo().Assembly;
    //Opens the Word template document
    using (WordDocument document = new WordDocument(assembly.GetManifestResourceStream("CreateWordSample.Assets.Letter Formatting.docx"), FormatType.Docx))
    {
         string[] fieldNames = { "ContactName", "CompanyName", "Address", "City", "Country", "Phone"};
         string[] fieldValues = { "Nancy Davolio", "Syncfusion", "507 - 20th Ave. E.Apt. 2A", "Seattle, WA", "USA", "(206) 555-9857-x5467" };
         //Performs the mail merge
         document.MailMerge.Execute(fieldNames, fieldValues);
         MemoryStream stream = new MemoryStream();
         //Saves the Word document to stream in DOCX format. 
        document.Save(stream, FormatType.Docx);
        //Saves the stream as a file in the device and invoke it for viewing
        SaveAndroid androidSave = new SaveAndroid();
        await androidSave.SaveAndView("Result.docx", "application/msword", stream, this);
}
  1.  Add the SaveAndroid class to the project where the stream will be saved to a physical file and the file can be opened for viewing.

The code for SaveAndroid class has been given below.

C#

class SaveAndroid
{
  //Method to save document as a file in Android and view the saved document
  public async Task SaveAndView(string fileName, String contentType, MemoryStream stream, AppCompatActivity activity)
  {
    string root = null;
    //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())
    {
      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.AddFlags(ActivityFlags.NewTask);
      intent.SetDataAndType(path, mimeType);
      activity.StartActivity(Intent.CreateChooser(intent, "Choose App"));
    }
  }
}
  1. Compile and execute the application. Now this application creates a mail merge Word document.
    Note:

    For the Word document to be read and written in the android device, the storage permission must be given for the deployed application. To read/write with the external storage location enable the required permissions in Android Manifest.

Add read, write permission in Android manifest

A complete working example of mail merge Word document in Xamarin.Android can be downloaded from mail merge Word document.zip.

By executing the program, you will get the Word document as follows. Mail merge output Word document

Take a moment to peruse the documentation, where you can find basic Word document processing options along with features like merge and split documents, find and replace text in the Word document, and most importantly PDF conversions with code examples.

Explore more about the rich set of Syncfusion Word Framework features.

An online example to perform mail merge in Word document.

See Also:

Mail Merge Word document in Xamarin.iOS

Mail Merge Word document in Xamarin

Mail Merge Word document in C#

Mail Merge Word document in Windows Forms

Mail Merge Word document in WPF

Mail Merge Word document in UWP

Mail Merge Word document in ASP.NET

Mail Merge Word document in ASP.NET MVC

Mail Merge Word document in ASP.NET Core

Note:

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.



Conclusion

I hope you enjoyed learning how to mail merge Word document in Xamarin.Android.

You can refer to our Xamarin. Android Word feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Xamarin. Android Word example 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 forumsDirect-Trac, or feedback portal. We are always happy to assist you!


Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied