1、判断要导出的文件夹是否存在,不存在则创建
//判断文件夹是否存在
//Application.StartupPath项目运行根目录
if (!Directory.Exists(Application.StartupPath + @"\CSV"))
{
//创建文件夹
Directory.CreateDirectory(Application.StartupPath + @"\CSV");
}string time = DateTime.Now.ToString("yyyyMMddHHmmss-");
string path = Application.StartupPath + @"\CSV\" + time+ FileName + ".CSV";
2、创建StringBuilder来封装字符串
StringBuilder sCsvContent= new System.Text.StringBuilder();
3、循环datatable数据存入StringBuilder
int colcount= dt.Columns.Count;
//标题
for (int i = 0; i < colcount; i++)
{
sCsvContent.Append(dt.Columns[i].ColumnName);//标题名
sCsvContent.Append(i == colcount - 1 ? "\r\n" : ",");//分割或换行
}//数据
foreach (System.Data.DataRow row in dt.Rows)
{
for (int i = 0; i < colcount; i++)
{
sCsvContent.Append(row[i].ToString().Trim() + "\t");
sCsvContent.Append(i == colcount - 1 ? "\r\n" : ",");
}
}
4、创建文件并写入数据
File.WriteAllText(path, sCsvContent.ToString(), Encoding.UTF8);