C# 点击按钮事件,Excel表格导出SQL Server数据库表信息

前言

C# 点击按钮事件,Excel表格导出SQL Server数据库表信息,合适新手小白使用,写的会很详细,也可以直接复制代码。


一、环境

语言:C#

开发工具:VS2019 ,winform窗体

数据库:SQL Server 2012

Excel:office2010

二、使用步骤

1.数据库

简单的表结构:
在这里插入图片描述

简单的数据结构:
在这里插入图片描述

2.简单的winform界面

拖两个Button(一个查询、一个导出)和一个DataGridView:

在这里插入图片描述
DataGridView表格数据添加列,绑定数据(DataPropertyName)列名和数据库中的要一致;文本(text)就是展示的列名。

后台代码

  1. App.config文件:连接数据库字符串

Initial Catalog=“数据库名称”

<configuration>
	<!--连接字符串(只需要加上这一段)-->
	<connectionStrings>
		<add name="connectionString" connectionString="Persist Security Info=False;User ID=sa;pwd=123456;Initial Catalog=demo;Data Source=." providerName="System.Data.SqlClient"/>
	</connectionStrings>
	
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
</configuration>
  1. 添加引用:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
  1. 链接字符串

“链接字符串”与“public Form1()”同级

		#region 链接字符串
        private readonly string Connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString();

        public string Conn
        {
            get
            {
                return this.Connstring;
            }
        }

        SqlConnection myCn = null;
        SqlDataAdapter sda = null;
        #endregion

        public Form1()
        {
            InitializeComponent();
        }
  1. 点击“查询数据”按钮事件
		//查询数据库信息
        private void button1_Click(object sender, EventArgs e)
        {
            dataGridViewAll();//定义的方法
        }
        
        #region datagridview 查询全部数据
        private void dataGridViewAll()
        {
            string selStr = "select * from StuInfo";//查询数据库语句,根据个人需要所变动
            DataTable dt = selSQL(selStr);
            dataGridView1.DataSource = dt;
            dataGridView1.AllowUserToAddRows = false;
            if (dataGridView1.Rows.Count > 0)
            {
                dataGridView1.CurrentCell = dataGridView1[0, dataGridView1.Rows.Count - 1];
            }
        }
        #endregion

        #region 查询数据库
        private DataTable selSQL(string strSql)
        {
            myCn = new SqlConnection(this.Conn);
            sda = new SqlDataAdapter(strSql, myCn);
            try
            {
                myCn.Open();
                DataSet ds = new DataSet("ds");
                sda.Fill(ds);//如果此处报错,请查询数据库名是否匹配
                return ds.Tables[0];
            }
            finally
            {
                myCn.Close();
                myCn.Dispose();
                sda.Dispose();
            }
        }
        #endregion
  1. 点击“Excel导出”按钮事件
		//点击“Excel导出”按钮
		private void button2_Click(object sender, EventArgs e)
        {
            string selStr = "select * from StuInfo";//查询数据库语句,根据个人需要所变动
            DataTable dt = selSQL(selStr);
            SaveFileDialog kk = new SaveFileDialog();//引用using System.Windows.Forms;
            kk.Title = "保存EXECL文件";
            kk.Filter = "EXECL文件(*.xls) |*.xls |所有文件(*.*) |*.*";
            kk.FilterIndex = 1;
            if (kk.ShowDialog() == DialogResult.OK)
            {
                //保存文件名
                string FileName = kk.FileName;
                if (File.Exists(FileName))File.Delete(FileName);
                FileStream objFileStream;
                StreamWriter objStreamWriter;
                string strLine = "";
                objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
                objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    strLine = strLine + dt.Columns[i].Caption.ToString() + Convert.ToChar(9);
                }
                objStreamWriter.WriteLine(strLine);
                strLine = "";

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (dt.Rows[i].ItemArray[j] == null)
                            strLine = strLine + " " + Convert.ToChar(9);
                        else
                        {
                            string rowstr = "";
                            rowstr = dt.Rows[i].ItemArray[j].ToString();
                            if (rowstr.IndexOf("\r\n") > 0)
                                rowstr = rowstr.Replace("\r\n", " ");
                            if (rowstr.IndexOf("\t") > 0)
                                rowstr = rowstr.Replace("\t", " ");
                            strLine = strLine + rowstr + Convert.ToChar(9);
                        }
                    }
                    objStreamWriter.WriteLine(strLine);
                    strLine = "";
                }
                objStreamWriter.Close();
                objFileStream.Close();
                MessageBox.Show(this, "导出Excel成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

总结

以上就是今天要讲的内容,本人比较啰嗦,文章写的有点细,代码可以直接复制使用,所需要修改的地方,也注释出来了,如果有需要的可以复制粘贴(一个图像一个图像的粘贴哦,代码分工写清楚了)。有问题也可以评论告诉我哦!

本人记录自己所需要记录的代码,如果可以帮到你们的,也很开心,喜欢点个赞!
(「・ω・)「嘿

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值