使用SaveFileDialog将DataTable文件保存成csv文件
public static bool SaveDatatableToCSV(DataTable dt)
{
bool createFLAG = false;
try
{
StringBuilder sb = new StringBuilder();
string line = "";
if (dt != null && dt.Rows.Count > 0)
{
//table head
for (int i = 0; i < dt.Columns.Count; i++)
{
line += string.Format("\"{0}\",", dt.Columns[i].ColumnName);
}
line = line.TrimEnd(',');
sb.AppendLine(line);
//every row
foreach (DataRow row in dt.Rows)
{
line = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
line += string.Format("\"{0}\",", row[j].ToString().Replace("\"", "\"\""));
}
line = line.TrimEnd(',');
sb.AppendLine(line);
}
SaveFileDialog mopen = new SaveFileDialog();
mopen.Title = "保存csv文件";
mopen.Filter = "csv文件(*.csv)|*.csv";
if (mopen.ShowDialog() == DialogResult.OK)
{
string csvName = mopen.FileName;
File.WriteAllText(csvName, sb.ToString(), Encoding.UTF8);
}
}//end if
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return createFLAG;
}