Hi Waghmare,
Refer below code.
Here i am reading the content from Text file.
HTML
<asp:Button ID="btnExportCsv" runat="server" Text="Export To CSV" OnClick="ExportCSV" />
Namespaces
C#
using System.Data;
using System.IO;
using System.Text;
VB.Net
Imports System.Data
Imports System.IO
Imports System.Text
Code
protected void ExportCSV(object sender, EventArgs e)
{
string csvPath = Server.MapPath("~/Files/Customers.txt");
string[] csvData = File.ReadAllLines(csvPath);
DataTable dt = new DataTable();
for (int i = 0; i < csvData.Length; i++)
{
string[] data = csvData[i].Split(',');
if (i == 0)
{
dt.Columns.Add(data[0]);
dt.Columns.Add(data[1]);
dt.Columns.Add(data[2]);
dt.Columns.Add(data[3]);
dt.Columns.Add(data[4]);
}
else
{
dt.Rows.Add(data[0], data[1], data[2], data[3], data[4] + "," + data[4]);
}
}
StringBuilder sb = new StringBuilder();
for (int k = 0; k < dt.Columns.Count; k++)
{
sb.Append(dt.Columns[k].ColumnName + ',');
}
sb.Append("\r\n");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
sb.Append(dt.Rows[i][k].ToString().Replace(",", ";") + ',');
}
sb.Append("\r\n");
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Data.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
VB.Net
Protected Sub ExportCSV(ByVal sender As Object, ByVal e As EventArgs)
Dim csvPath As String = Server.MapPath("~/Files/Customers.txt")
Dim csvData As String() = File.ReadAllLines(csvPath)
Dim dt As DataTable = New DataTable()
For i As Integer = 0 To csvData.Length - 1
Dim data As String() = csvData(i).Split(","c)
If i = 0 Then
dt.Columns.Add(data(0))
dt.Columns.Add(data(1))
dt.Columns.Add(data(2))
dt.Columns.Add(data(3))
dt.Columns.Add(data(4))
Else
dt.Rows.Add(data(0), data(1), data(2), data(3), data(4) & "," & data(4))
End If
Next
Dim sb As StringBuilder = New StringBuilder()
For k As Integer = 0 To dt.Columns.Count - 1
sb.Append(dt.Columns(k).ColumnName + ","c)
Next
sb.Append(vbCrLf)
For i As Integer = 0 To dt.Rows.Count - 1
For k As Integer = 0 To dt.Columns.Count - 1
sb.Append(dt.Rows(i)(k).ToString().Replace(",", ";") + ","c)
Next
sb.Append(vbCrLf)
Next
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=Data.csv")
Response.Charset = ""
Response.ContentType = "application/text"
Response.Output.Write(sb.ToString())
Response.Flush()
Response.End()
End Sub
Screenshot