//Data Tabel
//HTML
<asp:Button ID="btnExport" runat="server" Text="Button" OnClick="btnExport_Click" />
//Code Behind
protected void
btnExport_Click(object sender, EventArgs e)
{
DataTable dt = GetData();
StringBuilder builder = new
StringBuilder();
var count = 0;
// write header in String Builder
foreach (DataColumn
column in dt.Columns)
{
count++;
string content = column.ColumnName + "";
content = content.Replace("\"",
"\"\"");
builder.Append(string.Format("{0}{1}{0}", Convert.ToChar(34),
content));
if (count < dt.Columns.Count)
builder.Append(",");
}
builder.Append(Environment.NewLine);
//Write content in String Builder
foreach (DataRow
row in dt.Rows)
{
for (int i = 0; i
< row.ItemArray.Length; i++)
{
if (!Convert.IsDBNull(row[i]))
{
string content = row[i].ToString() + "";
content = content.Replace("\"",
"\"\"");
builder.Append(string.Format("{0}{1}{0}", Convert.ToChar(34),
content));
if (i < row.ItemArray.Length - 1)
builder.Append(",");
}
}
builder.Append(Environment.NewLine);
}
// get file and write inside file
using (var
streamWriter = new StreamWriter(@"C://Users//Vipin Gehlot//Desktop//yy.csv",
false, Encoding.UTF8))
{
streamWriter.Write(builder.ToString());
streamWriter.Flush();
streamWriter.Close();
}
}
}
No comments:
Post a Comment