/// <summary>
/// 写入CSV文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="dt">数据源</param>
private void writeCsv(string path, DataTable dt)
{
using (StreamWriter sw = new StreamWriter(path, false, Encoding.Default))
{
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(Environment.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write("\"" + dr[i].ToString().Replace("\"", "\"\"") + "\"");
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(Environment.NewLine);
}
}
//判断文件是否生成成功
while (!File.Exists(path))
{
System.Threading.Thread.Sleep(1000);
}
}