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.
- Create a windows application.
- Add a new class (utility class) to the application (which contains the method for retrieving the file content and creating the document file).
- 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).
- 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">
Join the conversation! Your thoughts help the community grow.