01.
using
System;
02.
using
System.Collections.Generic;
03.
using
System.Linq;
04.
using
System.Web;
05.
using
System.Web.UI;
06.
using
System.Web.UI.WebControls;
07.
using
System.IO;
08.
using
System.Data.OleDb;
09.
using
System.Data;
10.
using
System.Data.SqlClient;
11.
using
System.Collections;
12.
using
System.Configuration;
13.
using
System.Web.Security;
14.
using
System.Web.UI.HtmlControls;
15.
using
System.Web.UI.WebControls.WebParts;
16.
using
System.Xml.Linq;
17.
using
System.Reflection;
18.
using
System.Text;
19.
using
System.Text.RegularExpressions;
20.
using
System.Net;
21.
using
System.Net.Sockets;
22.
using
System.Web.Configuration;
23.
24.
namespace
testexcel
25.
{
26.
public
partial
class
createcsv : System.Web.UI.Page
27.
{
28.
protected
void
Page_Load(
object
sender, EventArgs e)
29.
{
30.
Response.Charset =
"tis-620"
;
31.
}
32.
33.
protected
void
Button1_Click(
object
sender, EventArgs e)
34.
{
35.
DataTable dt =
new
DataTable();
36.
dt.Columns.Add(
"ID"
);
37.
dt.Columns.Add(
"Name"
);
38.
dt.PrimaryKey =
new
DataColumn[] { dt.Columns[
"ID"
] };
39.
40.
DataRow dr = dt.NewRow();
41.
dr[
"ID"
] = 1;
42.
dr[
"name"
] =
"ทดสอบ"
;
43.
dt.Rows.Add(dr);
44.
45.
dr = dt.NewRow();
46.
dr[
"ID"
] = 2;
47.
dr[
"name"
] =
"B"
;
48.
dt.Rows.Add(dr);
49.
50.
dr = dt.NewRow();
51.
dr[
"ID"
] = 3;
52.
dr[
"name"
] =
"C"
;
53.
dt.Rows.Add(dr);
54.
55.
CreateCSVFile(dt,
"c:\\dell\\csvData.csv"
);
56.
}
57.
public
void
CreateCSVFile(DataTable dt,
string
strFilePath)
58.
{
59.
60.
StreamWriter sw =
new
StreamWriter(strFilePath,
false
);
61.
62.
63.
64.
int
iColCount = dt.Columns.Count;
65.
for
(
int
i = 0; i < iColCount; i++)
66.
{
67.
sw.Write(dt.Columns[i]);
68.
if
(i < iColCount - 1)
69.
{
70.
sw.Write(
","
);
71.
}
72.
}
73.
sw.Write(sw.NewLine);
74.
75.
foreach
(DataRow dr
in
dt.Rows)
76.
{
77.
for
(
int
i = 0; i < iColCount; i++)
78.
{
79.
if
(!Convert.IsDBNull(dr[i]))
80.
{
81.
sw.Write(dr[i].ToString());
82.
}
83.
84.
if
(i < iColCount - 1)
85.
{
86.
sw.Write(
","
);
87.
}
88.
}
89.
sw.Write(sw.NewLine);
90.
}
91.
sw.Close();
92.
}
93.
}
94.
}