Hi Appache,
Please refer below sample.
Form Design
Namespaces
C#
using System.IO;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Office.Interop.Word;
Code
C#
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = GetData("");
dataGridView1.AllowUserToAddRows = false;
//Add the Button Column.
DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
buttonColumn.HeaderText = "";
buttonColumn.Width = 60;
buttonColumn.Name = "buttonColumn";
buttonColumn.Text = "Export";
buttonColumn.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Insert(3, buttonColumn);
}
private System.Data.DataTable GetData(string customerId)
{
string constring = @"Data Source=.\SQL2019;Initial Catalog=AjaxSamples;User id=sa;password=password";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers WHERE CustomerId = @CustomerId OR @CustomerId IS NULL", con))
{
cmd.Parameters.AddWithValue("@CustomerId", !string.IsNullOrEmpty(customerId) ? customerId : (object)DBNull.Value);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (System.Data.DataTable dt = new System.Data.DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 3)
{
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
System.Data.DataTable dt = this.GetData(row.Cells["CustomerId"].Value.ToString());
//Table start.
string html = "<p><b>Customer Details</b></p><table cellpadding='5' cellspacing='0' style='border: 1px solid #ccc;font-size: 9pt;font-family:arial'>";
//Adding HeaderRow.
html += "<tr>";
foreach (DataColumn column in dt.Columns)
{
html += "<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + column.ColumnName + "</th>";
}
html += "</tr>";
//Adding DataRow.
html += "<tr>";
foreach (object item in dt.Rows[0].ItemArray)
{
if (item != null)
{
html += "<td style='width:120px;border: 1px solid #ccc'>" + item.ToString() + "</td>";
}
else
{
html += "<td style='width:120px;border: 1px solid #ccc'></td>";
}
}
html += "</tr>";
//Table end.
html += "</table>";
//Save the HTML string as HTML File.
string htmlFilePath = @"E:\Files\DataGridView.htm";
File.WriteAllText(htmlFilePath, html);
//Convert the HTML File to Word document.
_Application word = new Microsoft.Office.Interop.Word.Application();
_Document wordDoc = word.Documents.Open(FileName: htmlFilePath, ReadOnly: false);
wordDoc.SaveAs(FileName: @"E:\Files\DataGridView.doc", FileFormat: WdSaveFormat.wdFormatRTF);
((_Document)wordDoc).Close();
((_Application)word).Quit();
//Delete the HTML File.
File.Delete(htmlFilePath);
}
}
Screenshot