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
;
}
}
}