设为首页 加入收藏

TOP

C#中将DataTable中数据导出到csv文件中
2014-11-24 14:34:34 来源: 作者: 【 】 浏览:1
Tags:中将 DataTable 数据 导出 csv 文件

protected void Button1_Click(object sender, EventArgs e)
{
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);


}


///


/// Export the data from datatable to CSV file
///

///
public void ExportDataGridToCSV(DataTable dt)
{
string strFile = "";
string path = "";

//File info initialization
strFile = "test";
strFile = strFile + DateTime.Now.ToString("yyyyMMddhhmmss");
strFile = strFile + ".csv";
path = Server.MapPath(strFile);



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("\t");
}
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();


DownLoadFile(path);
}


private bool DownLoadFile(string _FileName)
{
try
{
System.IO.FileStream fs = System.IO.File.OpenRead(_FileName);
byte[] FileData = new byte[fs.Length];
fs.Read(FileData, 0, (int)fs.Length);
Response.Clear();
Response.AddHeader("Content-Type", "application/notepad");
string FileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(_FileName));
Response.AddHeader("Content-Disposition", "inline;filename=" + System.Convert.ToChar(34) + FileName + System.Convert.ToChar(34));
Response.AddHeader("Content-Length", fs.Length.ToString());
Response.BinaryWrite(FileData);
fs.Close();
System.IO.File.Delete(_FileName);
Response.Flush();
Response.End();
return true;
}
catch (Exception ex)
{
ex.Message.ToString();
return false;
}
}



///


/// Delete special symbol
///

///
///
public string DelQuota(string str)
{
string result = str;
string[] strQuota ={ "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", " " };
for (int i = 0; i < strQuota.Length; i++)
{
if (result.IndexOf(strQuota[i]) > -1)
result = result.Replace(strQuota[i], "");
}
return result;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C#读取CSV文件的方法 下一篇C#将jpg格式图片合成到bmp格式图..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: