Hi PRA,
Refer the below sample code and modify it as per your requirement.
C#
protected void Search(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] {
new DataColumn("LastName"), new DataColumn("Name"),new DataColumn("FatherName"),
new DataColumn("Birthday"),new DataColumn("Adress") });
dt.Rows.Add("Pulodov", "Rustam", "Abdulloevich", "22.12.1987", "city Dushanbe");
dt.Rows.Add("Soliev", "Firuzjon", "Mirzonovich", "16.06.1988", "city Hisor");
dt.Rows.Add("Malaev", "Nurullo", "Karimovich", "25.03.1986", "city Dushanbe");
if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
{
if (dt.Rows.Count > 0)
{
DataTable dtFinal = dt.Select("LastName = '" + txtSearch.Text.Trim() + "'").CopyToDataTable();
object fileName = Server.MapPath("~/Files/Test.doc");
Word.Application word = new Word.Application();
Word.Document doc = new Word.Document();
object missing = System.Type.Missing;
try
{
doc = word.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
doc.Activate();
bool lastNameChanged = false, nameChanged = false, fatherNameChanged = false, birthdayChanged = false, adressChanged = false;
foreach (Microsoft.Office.Interop.Word.Range docRange in doc.Words)
{
if (docRange.Text.Trim() == "LastName")
{
if (!lastNameChanged)
{
docRange.Text = docRange.Text.Replace("LastName", "LastName: " + dtFinal.Rows[0]["LastName"].ToString());
lastNameChanged = true;
}
}
else if (docRange.Text.Trim() == "Name")
{
if (!nameChanged)
{
docRange.Text = docRange.Text.Replace("Name", "Name: " + dtFinal.Rows[0]["Name"].ToString());
nameChanged = true;
}
}
else if (docRange.Text.Trim() == "FatherName")
{
if (!fatherNameChanged)
{
docRange.Text = docRange.Text.Replace("FatherName", "FatherName: " + dtFinal.Rows[0]["FatherName"].ToString());
fatherNameChanged = true;
}
}
else if (docRange.Text.Trim() == "Birthday")
{
if (!birthdayChanged)
{
docRange.Text = docRange.Text.Replace("Birthday", "Birthday: " + dtFinal.Rows[0]["Birthday"].ToString());
birthdayChanged = true;
}
}
else if (docRange.Text.Trim() == "Adress")
{
if (!adressChanged)
{
docRange.Text = docRange.Text.Replace("Adress", "Adress: " + dtFinal.Rows[0]["Adress"].ToString());
adressChanged = true;
}
}
}
foreach (Microsoft.Office.Interop.Word.Range docRange in doc.Words)
{
if (docRange.Text.Trim() == ":")
{
docRange.Text = docRange.Text.Replace(":", " ");
}
}
doc.Save();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
doc.Close(ref missing, ref missing, ref missing);
((Word._Application)word).Quit();
}
}
}
}
Screenshot