C#中怎么把数据库的数据导出成word
1个回答
展开全部
首先连接数据库,查找具体的数据表,然后将数据表显示在dataGridView中
示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
SqlConnection conn; //数据库连接
private void button1_Click(object sender, EventArgs e)
{
try
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
//执行的SQL命令
cmd.CommandText = string.Format("select Top 1000 * from [data base name].[dbo].[table name]"); //双引号内的SQL命令根据你的要求修改
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, conn);
dtSql = new DataTable();
da.Fill(dtSql); //将查找的结果给dataTable
da.Dispose();
dataGridView1.DataSource = dtSql; //dataTable显示在dataGridView中
dataGridView1.Refresh(); //刷新表
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
SqlConnection conn; //数据库连接
private void button1_Click(object sender, EventArgs e)
{
try
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
//执行的SQL命令
cmd.CommandText = string.Format("select Top 1000 * from [data base name].[dbo].[table name]"); //双引号内的SQL命令根据你的要求修改
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, conn);
dtSql = new DataTable();
da.Fill(dtSql); //将查找的结果给dataTable
da.Dispose();
dataGridView1.DataSource = dtSql; //dataTable显示在dataGridView中
dataGridView1.Refresh(); //刷新表
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询