Tuesday 16 January 2018

ASP.NET:How to Search and replace text in word file/document using C#/VB.NET ||Find and replace text in word file/document using C#/VB.NET

Hi friends,in this article I will explain about How to find and replace text in word file/document using C#/VB.NET
sampleDoc.docx
Name <<Name>>
Welcome  <<Name>>
DepartmentName is  <<DepartmentName>>
Your Date of joining is  <<DOJ>>









ASP.NET:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ASP.NET:Find and replace in word doc using C#/VB.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnDownload" runat="server" Text="Download"
            onclick="btnDownload_Click" />
    </div>
    </form>
</body>
</html>

In C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using DocumentFormat.OpenXml.Wordprocessing;

public partial class MergeDoc : System.Web.UI.Page
{
    string searchWord = string.Empty;
    string Replaceword = string.Empty;

    protected void btnDownload_Click(object sender, EventArgs e)
    {
        string Temp_FileName = "sampleDoc.docx";
        string templateDoc = string.Format("{0}{1}", Server.MapPath("~/Documents/"), Temp_FileName);
        string filename = Temp_FileName;
        string newfilename = string.Empty;
        int fileExtPos = filename.LastIndexOf(".");
        if (fileExtPos >= 0)
            newfilename = filename.Substring(0, fileExtPos) + ".docx";
        DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/DownlodedDocs/"));
        FileInfo[] files = dir.GetFiles(filename);
        foreach (FileInfo file in files)
            if (file.Name == filename)
            {
                DirectoryInfo dir1 = new DirectoryInfo(Server.MapPath("~/Documents/"));
                FileInfo[] files1 = dir1.GetFiles();
                foreach (FileInfo file1 in files1)
                    if (file1.Name == newfilename)
                    {
                        file1.Delete();
                    }
                file.CopyTo(Server.MapPath("~/Documents/" + newfilename));
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
                SqlCommand cmd = new SqlCommand("select Name, DepartmentName,DOJ from employee where emp_id=1", con);
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                string[] arr = { "Name", "DepartmentName", "DOJ" };
                /////First Way
                using (WordprocessingDocument doc = WordprocessingDocument.Open(templateDoc, true))
                {
                    var body = doc.MainDocumentPart.Document.Body;
                    var paras = body.Elements<Paragraph>();
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < arr.Length; i++)
                        {
                            searchWord = "<<" + arr[i] + ">>";
                            Replaceword = ds.Tables[0].Rows[0][i].ToString();
                            foreach (var para in paras)
                            {
                                foreach (var run in para.Elements<Run>())
                                {
                                    foreach (var text in run.Elements<Text>())
                                    {
                                        if (text.Text.Contains(searchWord))
                                        {
                                            text.Text = text.Text.Replace(searchWord, Replaceword);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    doc.Close();
                }
            }
        renderWordDoc(newfilename);
    }

    public void renderWordDoc(string saveasfile)
    {
        try
        {
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + "MergeDoc.docx");
            Response.TransmitFile(Server.MapPath("~/Documents/" + "sampleDoc.docx"));
            Response.End();
        }

        catch (System.Threading.ThreadAbortException ex)
        {
            throw ex;
        }
    }
    ////second way
    private void CreateSampleWordDocument()
    {

        string sourceFile = Path.Combine(Server.MapPath("~/Documents/sampleDoc.docx"));
        string destinationFile = Path.Combine(Server.MapPath("~/Documents/New.docx"));
        try
        {
            // Create a copy of the template file and open the copy
            File.Copy(sourceFile, destinationFile, true);
            using (WordprocessingDocument doc = WordprocessingDocument.Open(destinationFile, true))
            {
                var body = doc.MainDocumentPart.Document.Body;
                var paras = body.Elements<Paragraph>();

                foreach (var para in paras)
                {
                    foreach (var run in para.Elements<Run>())
                    {
                        foreach (var text in run.Elements<Text>())
                        {
                            if (text.Text.Contains("Name"))
                            {
                                text.Text = text.Text.Replace("Name", "Kishore");
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateSampleWordDocument();
    }
}

In VB.NET:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports DocumentFormat.OpenXml.Packaging
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports DocumentFormat.OpenXml.Wordprocessing

Partial Public Class MergeDoc
    Inherits System.Web.UI.Page
    Private searchWord As String = String.Empty
    Private Replaceword As String = String.Empty

    Protected Sub btnDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim Temp_FileName As String = "sampleDoc.docx"
        Dim templateDoc As String = String.Format("{0}{1}", Server.MapPath("~/Documents/"), Temp_FileName)
        Dim filename As String = Temp_FileName
        Dim newfilename As String = String.Empty
        Dim fileExtPos As Integer = filename.LastIndexOf(".")
        If fileExtPos >= 0 Then
            newfilename = filename.Substring(0, fileExtPos) & ".docx"
        End If
        Dim dir As New DirectoryInfo(Server.MapPath("~/DownlodedDocs/"))
        Dim files As FileInfo() = dir.GetFiles(filename)
        For Each file As FileInfo In files
            If file.Name = filename Then
                Dim dir1 As New DirectoryInfo(Server.MapPath("~/Documents/"))
                Dim files1 As FileInfo() = dir1.GetFiles()
                For Each file1 As FileInfo In files1
                    If file1.Name = newfilename Then
                        file1.Delete()
                    End If
                Next
                file.CopyTo(Server.MapPath("~/Documents/" & newfilename))
                Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ConnectionString)
                Dim cmd As New SqlCommand("select Name, DepartmentName,DOJ from employee where emp_id=1", con)
                cmd.CommandType = CommandType.Text
                Dim da As New SqlDataAdapter(cmd)
                Dim ds As New DataSet()
                da.Fill(ds)
                Dim arr As String() = {"Name", "DepartmentName", "DOJ"}
                '''//First Way
                Using doc As WordprocessingDocument = WordprocessingDocument.Open(templateDoc, True)
                    Dim body = doc.MainDocumentPart.Document.Body
                    Dim paras = body.Elements(Of Paragraph)()
                    If ds.Tables(0).Rows.Count > 0 Then
                        For i As Integer = 0 To arr.Length - 1
                            searchWord = "<<" & arr(i) & ">>"
                            Replaceword = ds.Tables(0).Rows(0)(i).ToString()
                            For Each para As var In paras
                                For Each run As var In para.Elements(Of Run)()
                                    For Each text As var In run.Elements(Of Text)()
                                        If text.Text.Contains(searchWord) Then
                                            text.Text = text.Text.Replace(searchWord, Replaceword)
                                        End If
                                    Next
                                Next
                            Next
                        Next
                    End If
                    doc.Close()
                End Using
            End If
        Next
        renderWordDoc(newfilename)
    End Sub

    Public Sub renderWordDoc(ByVal saveasfile As String)
        Try
            Response.ContentType = "application/octet-stream"
            Response.AppendHeader("Content-Disposition", "attachment;filename=" & "MergeDoc.docx")
            Response.TransmitFile(Server.MapPath("~/Documents/" & "sampleDoc.docx"))
            Response.[End]()

        Catch ex As System.Threading.ThreadAbortException
            Throw ex
        End Try
    End Sub
    '''/second way
    Private Sub CreateSampleWordDocument()

        Dim sourceFile As String = Path.Combine(Server.MapPath("~/Documents/sampleDoc.docx"))
        Dim destinationFile As String = Path.Combine(Server.MapPath("~/Documents/New.docx"))
        Try
            ' Create a copy of the template file and open the copy
            File.Copy(sourceFile, destinationFile, True)
            Using doc As WordprocessingDocument = WordprocessingDocument.Open(destinationFile, True)
                Dim body = doc.MainDocumentPart.Document.Body
                Dim paras = body.Elements(Of Paragraph)()

                For Each para As var In paras
                    For Each run As var In para.Elements(Of Run)()
                        For Each text As var In run.Elements(Of Text)()
                            If text.Text.Contains("Name") Then
                                text.Text = text.Text.Replace("Name", "Kishore")
                            End If
                        Next
                    Next
                Next
            End Using
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        CreateSampleWordDocument()
    End Sub
End Class

Output

Name  Kishore
Welcome  Kishore
DepartmentName is  SE
Your Date of joining is  01-01-2007



1 comment:

  1. It is very good blog and useful for students and developer , Thanks for sharing



    .Net Online Training

    ReplyDelete

© 2012-2018 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.