SIGN UP MEMBER LOGIN:    
ARTICLE

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

Posted by A V Mahesh Articles | Visual C# June 23, 2010
In this article we will see how to create word document without using COM component (Interop) or Third party API's.
Reader Level:
Download Files:
 

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);
    }
}

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor