- private void ExportBtn_Click(object sender, EventArgs e)
- {
- string cfig = ConfigurationManager.ConnectionStrings["peoplecon"].ConnectionString.ToString();//数据库连接
- try
- {
- using (FileStream fileStream = new FileStream(@"d:\a.txt", FileMode.OpenOrCreate))//指定路径和文件创建方式
- {
- using (StreamWriter streamwriter = new StreamWriter(fileStream))
- {
- using (SqlConnection cnn = new SqlConnection(cfig))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- DataSet ds = new DataSet();//创建一个DataSet
- string sql = "select * from people";
- SqlDataAdapter adapter = new SqlDataAdapter(sql, cnn);
- adapter.Fill(ds);//将数据填充到DataSet
- DataTable dt = ds.Tables[0];//建立一个DataTable
- for (int rows = 0; rows < dt.Rows.Count; rows++)//将DataTable中的数据写到txt文件中
- {
- string str = dt.Rows[rows][0].ToString() + "|" + dt.Rows[rows][1].ToString();
- streamwriter.WriteLine(str);
- }
- }
- }
- }
- MessageBox.Show("导出成功");
- }
-
- }
- catch
- {
- }
-
- }
- }
复制代码 |