Hi dnnyobi,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.IO;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.IO
Code
C#
private void Form2_Load(object sender, System.EventArgs e)
{
this.BindData();
}
protected void BindData()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
using (SqlCommand cmd = new SqlCommand("SELECT EmployeeID,FirstName+' '+LastName Name,Country,HomePhone FROM Employees", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
sda.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];
}
}
}
private void btnExport_Click(object sender, System.EventArgs e)
{
DataTable dt = new DataTable();
foreach (DataGridViewTextBoxColumn column in dataGridView1.Columns)
{
dt.Columns.Add(column.Name, column.ValueType);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dr = dt.NewRow();
foreach (DataGridViewTextBoxColumn column in dataGridView1.Columns)
{
if (row.Cells[column.Name].Value != null)
{
dr[column.Name] = row.Cells[column.Name].Value.ToString();
}
}
dt.Rows.Add(dr);
}
string filePath = "D:\\Result.txt";
DataTableToTextFile(dt, filePath);
}
private void DataTableToTextFile(DataTable dt, string outputFilePath)
{
int[] maxLengths = new int[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
maxLengths[i] = dt.Columns[i].ColumnName.Length;
foreach (DataRow row in dt.Rows)
{
if (!row.IsNull(i))
{
int length = row[i].ToString().Length;
if (length > maxLengths[i])
{
maxLengths[i] = length;
}
}
}
}
using (StreamWriter sw = new StreamWriter(outputFilePath, false))
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ColumnName.PadRight(maxLengths[i] + 2));
}
sw.WriteLine();
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (!row.IsNull(i))
{
sw.Write(row[i].ToString().PadRight(maxLengths[i] + 2));
}
else
{
sw.Write(new string(' ', maxLengths[i] + 2));
}
}
sw.WriteLine();
}
sw.Close();
}
}
VB.Net
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.BindData()
End Sub
Protected Sub BindData()
Dim con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("conString").ConnectionString)
Using cmd As SqlCommand = New SqlCommand("SELECT EmployeeID,FirstName+' '+LastName Name,Country,HomePhone FROM Employees", con)
cmd.CommandType = CommandType.Text
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
sda.Fill(ds)
Me.DataGridView1.DataSource = ds.Tables(0)
End Using
End Using
End Sub
Private Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
Dim dt As DataTable = New DataTable()
For Each column As DataGridViewTextBoxColumn In DataGridView1.Columns
dt.Columns.Add(column.Name, column.ValueType)
Next
For Each row As DataGridViewRow In DataGridView1.Rows
Dim dr As DataRow = dt.NewRow()
For Each column As DataGridViewTextBoxColumn In DataGridView1.Columns
If row.Cells(column.Name).Value IsNot Nothing Then
dr(column.Name) = row.Cells(column.Name).Value.ToString()
End If
Next
dt.Rows.Add(dr)
Next
Dim filePath As String = "D:\Result.txt"
DataTableToTextFile(dt, filePath)
End Sub
Private Sub DataTableToTextFile(ByVal dt As DataTable, ByVal outputFilePath As String)
Dim maxLengths As Integer() = New Integer(dt.Columns.Count - 1) {}
For i As Integer = 0 To dt.Columns.Count - 1
maxLengths(i) = dt.Columns(i).ColumnName.Length
For Each row As DataRow In dt.Rows
If Not row.IsNull(i) Then
Dim length As Integer = row(i).ToString().Length
If length > maxLengths(i) Then
maxLengths(i) = length
End If
End If
Next
Next
Using sw As StreamWriter = New StreamWriter(outputFilePath, False)
For i As Integer = 0 To dt.Columns.Count - 1
sw.Write(dt.Columns(i).ColumnName.PadRight(maxLengths(i) + 2))
Next
sw.WriteLine()
For Each row As DataRow In dt.Rows
For i As Integer = 0 To dt.Columns.Count - 1
If Not row.IsNull(i) Then
sw.Write(row(i).ToString().PadRight(maxLengths(i) + 2))
Else
sw.Write(New String(" "c, maxLengths(i) + 2))
End If
Next
sw.WriteLine()
Next
sw.Close()
End Using
End Sub
End Class
Exported Text File