Category >
LINQ
|| Published on :
Monday, September 21, 2020 || Views:
2704
||
C# - Datatable to CSV using LINQ
This article we are going to learn to convert Datatable to CSV in c# and explains the efficient way to write CSV files from Datatable
aspx source code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="datatable-CSV-linq.aspx.cs" Inherits="datatable_CSV_linq" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnConvert" runat="server" Text="datatable to CSV" OnClick="btnConvert_Click" />
</div>
</form>
</body>
</html>
code behind source code
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
public partial class datatable_CSV_linq : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public DataTable GetData()
{
DataTable dt = new DataTable();
try
{
dt.Columns.Add("CustomerId", typeof(int));
dt.Columns.Add("CustomerName", typeof(string));
dt.Columns.Add("ProductName", typeof(string));
dt.Columns.Add("Price", typeof(double));
dt.Rows.Add(1, "Shahrukh", "desktop", 65000);
dt.Rows.Add(2, "Salman", "keyboard", 1120);
dt.Rows.Add(3, "Amir", "RAM", 8900);
dt.Rows.Add(4, "Akshay", "Ryzen 5 3600", 20000);
dt.Rows.Add(5, "Dev", "Mouse", 596);
dt.Rows.Add(6, "Kishor", "RGB Fan", 400);
return dt;
}
catch (Exception ex)
{
return null;
}
finally
{
if (dt != null)
{
dt.Dispose();
dt = null;
}
}
}
protected void btnConvert_Click(object sender, EventArgs e)
{
try
{
DataTable dtCSV = new DataTable();
dtCSV = GetData();
if (dtCSV != null && dtCSV.Rows.Count > 0)
{
StringBuilder sb = new StringBuilder();
string[] columnNames = dtCSV.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dtCSV.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(Server.MapPath("/data.csv"), sb.ToString());
}
}
catch (Exception ex)
{
throw;
}
}
}