c# winform 将Excel2010表格数据导入到sqlserver2012

首先是界面设计,这个我就随便拉了三个控件 ,两个button,一个dataGridView,如图所示:

c# winform 将Excel2010表格数据导入到sqlserver2012_第1张图片

实现逻辑:用odbc将excel表格数据查出,存到 datatable, 然后把datatable数据填充到datagridview中

然后附上完整代码:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataTable dt = new DataTable();
        //数据库连接字段
        string connString = "server =192.168.1.222; uid = sa; pwd = *_*Wenz,a; database = test1";
        SqlConnection conn;
        private void button1_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                string fileName = fd.FileName;
                bind(fileName);
            }
        }
        private void bind(string fileName)
        {
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                 "Data Source=" + fileName + ";" +
                 "Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'";
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT *  FROM [sheet1$]", strConn);
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds);
                dt = ds.Tables[0];
                this.dataGridView1.DataSource = dt;
            }
            catch (Exception err)
            {
                MessageBox.Show("操作失败!" + err.ToString());
            }
        }
        //将Datagridview1的记录插入到数据库    
        private void button2_Click_1(object sender, EventArgs e)
        {
            conn = new SqlConnection(connString);
            conn.Open();
            if (dataGridView1.Rows.Count > 0)
            {
                DataRow dr = null;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dr = dt.Rows[i];
                    insertToSql(dr);
                }
                conn.Close();
                MessageBox.Show("导入成功!");
            }
            else
            {
                MessageBox.Show("没有数据!");
            }
        }
         private void insertToSql(DataRow dr)  
            {  
                //excel表中的列名和数据库中的列名一定要对应  
                string name = dr["name"].ToString();  
                string sex = dr["sex"].ToString();  
                string no = dr["no"].ToString();  
                string major = dr["major"].ToString();  
                string sql = "insert into student values('" + name + "','" + sex + "','" + no + "','" + major +"')";           
                SqlCommand cmd = new SqlCommand(sql, conn);             
                cmd.ExecuteNonQuery();  
            }  
    }

注意事项:

1.运行iis,将启动32位应用程序,设置为true,如图:

c# winform 将Excel2010表格数据导入到sqlserver2012_第2张图片

2.将项目生成改为64位,右击项目属性-生成 ,如图所示:

c# winform 将Excel2010表格数据导入到sqlserver2012_第3张图片

 

你可能感兴趣的:(c# winform 将Excel2010表格数据导入到sqlserver2012)