c#怎么将datatable导出到csv文件中 200
展开全部
//测试数据
DataTable dt = new DataTable();
dt.Columns.Add("test1");
dt.Columns.Add("test2");
dt.Columns.Add("test3");
dt.Columns.Add("test4");
dt.Columns.Add("test5");
for (int i = 0; i < 6; i++)
{
dt.Rows.Add();
dt.Rows[i][0] = "CN"+i.ToString();
dt.Rows[i][1] = "EN"+i.ToString();
dt.Rows[i][2] = "JN"+i.ToString();
dt.Rows[i][3] = "HK"+i.ToString();
dt.Rows[i][4] = "TW"+i.ToString();
}
ExportDataGridToCSV(dt);
//导出方法
public void ExportDataGridToCSV(DataTable dt)
{
string strFile = "";
string path = "";
strFile = "test";
strFile = strFile + DateTime.Now.ToString("yyyyMMddhhmmss");
strFile = strFile + ".csv";
path = "d:\Test" + strFile;//save path
System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());
//Tabel header
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ColumnName);
sw.Write(",");
}
sw.WriteLine("");
//Table body
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
sw.Write(DelQuota(dt.Rows[i][j].ToString()));
sw.Write("\t");
}
sw.WriteLine("");
}
sw.Flush();
sw.Close();
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询