Create Word Document without using COM component (Interop) or Third party API's


In most of the application office automation is sometime required and to accomplish that most of the time we use to write code using COM (Interop dll) component or using third party API's. But as per application stand point of view it's not advisable to use COM components for office automation as far as the development platform is Dot Net. 

So in order to accomplish the same task without using COM (Interop dll) component or third party API's. We need to follow below steps which will do the trick for office automation.
  1. Create a windows application.
  2. Add a new class (utility class) to the application (which contains the method for retrieving the file content and creating the document file).
  3. Create an html template file (which only contains the design and key data fields). Key data field are those fields which starts and ends with ($) sign (example: $NameOfApplicant$). The value for this key data field is replaced from UI (code behind) dynamically (after the file is loaded into memory).
  4. Add a button to the default form and call the methods provided in the utility class on button click event.
Code snippet of Utility class

public static class Utility
{
    /// <summary>
    /// Method used to return the HTML Template String from HTML File ....
    /// </summary>
    /// <param name="filePath">template file path</param>
    /// <returns></returns>
    public static string GetTemplateString(string filePath)
    {
        string templateString = string.Empty;
        StreamReader re = null;
        try
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                re = File.OpenText(filePath);
                if (re != null)
                    templateString = re.ReadToEnd();
            }
        }
        catch (Exception exp)
        {
            templateString = string.Empty;
        }
        finally
        {
            if (re != null) re.Close();
            if (re != null) re.Dispose();
        }
        return templateString;
    }
    /// <summary>
    /// Method used to create datafile (txt / doc both).
    /// </summary>
    /// <param name="filecontent">content of file with actual data</param>
    /// <param name="filePath">file path with name & extention</param>
    /// <returns></returns>
    public static bool CreateDataFile(string filecontent, string filePath)
    {
        bool _IsFileCreated = true;
        StreamWriter sw = new StreamWriter(filePath);
        try
        {
            sw.Write(filecontent);
        }
        catch
        {
            _IsFileCreated = false;
        }
        finally
        {
            sw.Close();
            sw.Dispose();
        }
        return _IsFileCreated;
    }
}

Sample of html Template file

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title></title>
</head>
<body>
    <table border="0" cellpadding="0" cellspacing="0" width="100%">
        <tr>
            <td style="font-family: Calibri; font-size: 8pt;">
                <table border="0" cellpadding="0" cellspacing="0" width="100%">
                    <tr><td colspan="3">BIRTH CRTIFICATE</td></tr>
                    <tr style="height:10px;"><td colspan="3"></td></tr>
                    <tr>
                        <td width="150" align="left">Name Of Applicant</td>
                        <td width="15" align="center">:</td>
                        <td>$NameOfApplicant$</td>
                    </tr>
                    <tr>
                        <td width="150" align="left">District</td>
                        <td width="15" align="center">:</td>
                        <td>$District$</td>
                    </tr>
                    <tr>
                        <td width="150" align="left">Date Of Birth</td>
                        <td width="15" align="center">:</td>
                        <td>$DateOfBirth$</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>

Code snippet of Button Click Event

private void btnCreateDocument_Click(object sender, EventArgs e)
{
    string DirectoryPath = System.Text.RegularExpressions.Regex.Replace(Environment.CurrentDirectory, @"\\([^\\])+\\([^\\])+(\\)?$", "");
    // below is the HTML Template File Path.
    string DocumentTemplate = Utility.GetTemplateString(DirectoryPath + "\\CreateDocTemplate.htm");
    if (!string.IsNullOrEmpty(DocumentTemplate))
    {
        //if Template have Content than it replace the below text content with actual values.
        DocumentTemplate = DocumentTemplate.Replace("$NameOfApplicant$", "A.V.Mahesh Nair");
        DocumentTemplate = DocumentTemplate.Replace("$District$", "Malappuram");
        DocumentTemplate = DocumentTemplate.Replace("$DateOfBirth$", "7th Dec. 1980");
        // from here you can create any two type of file (doc / html).
        // first parameter is the Actual HTML Content with data and second parameter is the documnet file path.
        // This method automatically creats the doc file at the given location.
        string strTicks = DateTime.Now.Ticks.ToString();
        docFileNameWithPath = DirectoryPath + "\\" + strTicks + "CreateDoc.doc";
        Utility.CreateDataFile(DocumentTemplate, docFileNameWithPath);
        if (File.Exists(docFileNameWithPath))
        Process.Start(docFileNameWithPath);
    }
}

Up Next
    Ebook Download
    View all
    Learn
    View all