{
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "CSV文件|*.CSV";
saveDialog.InitialDirectory = "E:\\";
if (saveDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
else
{
string fileName = saveDialog.FileName;
DataSet ds = new DataSet();
ExportExcel_CSV(ds.Tables[0], fileName);
}
}
public void ExportExcel_CSV(System.Data.DataTable dt, string fileName)
{
FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
string str= "";
DataSet ds = new DataSet();
//写出列名称
for (int i = 0; i < dt.Columns.Count; i++)
{
str+= dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - 1)
{
str+= ",";
}
}
sw.WriteLine(str);
//写出各行数据
for (int i = 0; i < dt.Rows.Count; i++)
{
string tempStr = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
tempStr += dt.Rows[i][j].ToString();
if (j < dt.Columns.Count - 1)
{
tempStr += ",";
}
}
sw.WriteLine(tempStr );
}
sw.Close();
fs.Close();
MessageBox.Show("数据导出成功!");
}