下面是我做过的导出数据到Excel文件中,我是在窗体里设置SavaFileDialog的Filter属性的,它的属性为:Excel Files(*.xls)|*.xls "; 你试试看……代码如下所示:
private void btnExport_Click(object sender, EventArgs e)
{
if (sfdExport.ShowDialog() == DialogResult.OK)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\DataIO.mdf;
Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select * from T_Persons";
//打开现有文件以进行写入
using (FileStream fileStream = File.OpenWrite(sfdExport.FileName))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = reader.GetInt32(reader.GetOrdinal("Id"));
string name = reader.GetString(reader.GetOrdinal("Name"));
int age = reader.GetInt32(reader.GetOrdinal("Age"));
streamWriter.WriteLine(id + "|" + name + "|" + age);
}
MessageBox.Show("数据导出完成!");
}
}
}
}
}
}
} |