c# excel如何導入到sqlserver數據庫


最近在做這個如何把excel導入到數據庫中,經過多方查找,終於找到一個適合的,並且經過自己的完善可以正常使用(忘記原作者博客的鏈接地址了,敬請見諒)

  1. 首先是窗體的創建,文本框顯示文件的路徑,按鈕執行操作,DataGridView顯示導入的信息
  2. 代碼如下:可根據自己的需求進行修改,我是要導入之后就對我的另一窗體進行刷新,定義了委托,你們可以忽略。

            //定義委托
            public delegate void Refresh();
    
            //定義事件
            public event Refresh myRefresh;
            public ExcelRoprtForm()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                //選中導入的文件
                try
                {
                    //openFileDialog1.Filter = "Excel 文件|*.xls";//指定存放文件格式類型
                    OpenFileDialog fd = new OpenFileDialog();
                    fd.Filter = "Excel文件(*.xls,xlsx)|*.xls;*.xlsx";
                    if (fd.ShowDialog() == DialogResult.OK)
                    {
                        string fileName = fd.FileName.ToString();
                        this.textBox1.Text = fileName;
                    }
    
                }
                catch (Exception ee)
                {
                    MessageBox.Show("打開文件出錯!" + ee.Message.ToString());
                }
            }
    
            private DataSet xsldata(string filepath)
            {
                string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;IMEX=1'";
    
                //string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + filepath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
    
                System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon);
    
                string strCom = "SELECT * FROM [Sheet1$]";
    
                Conn.Open();
    
                System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);
    
                DataSet ds = new DataSet();
    
                myCommand.Fill(ds, "[Sheet1$]");
                dataGridView1.DataSource = ds.Tables[0];
                Conn.Close();
                return ds;
            }
            private void button2_Click(object sender, EventArgs e)
            {
                if (textBox1.Text == "")
                {
                    MessageBox.Show("請選擇要導入的Excel文檔!", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                string filepath = textBox1.Text;
                string strcon1 = ConfigurationManager.ConnectionStrings["connString"].ToString();
                SqlConnection conn = new SqlConnection(strcon1);//鏈接數據庫
                conn.Open();
                try
                {
                    DataSet ds = new DataSet();
                    //取得數據集
                    //調用上面的函數
                    ds = xsldata(filepath);
                    int errorcount = 0;//記錄錯誤信息條數
    
                    int insertcount = 0;//記錄插入成功條數
    
                    int updatecount = 0;//記錄更新信息條數
    
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        string carnumber = ds.Tables[0].Rows[i][0].ToString();
                        int carstatus = Convert.ToInt32(ds.Tables[0].Rows[i][1].ToString());
                        int cartype = Convert.ToInt32(ds.Tables[0].Rows[i][2].ToString());
                        string carbrand = ds.Tables[0].Rows[i][3].ToString();
    
                        if (carnumber != "" && carstatus != 0 && cartype != 0)
                        {
                            SqlCommand selectcmd = new SqlCommand("select count(*) from CarInfo where CarNumber='" + carnumber + "'", conn);
                            
                            int count = Convert.ToInt32(selectcmd.ExecuteScalar());
                            if (count > 0)
                            {
                                updatecount++;
                            }
                            else
                            {
                                SqlCommand insertcmd = new SqlCommand("insert into CarInfo(CarNumber,CarStatusID,CarTypeID,CarBrand) values(" + "'" + carnumber + "'," + carstatus + "," + cartype + ",'" + carbrand + "'" + ")", conn);
    
                                insertcmd.ExecuteNonQuery();
    
                                insertcount++;
    
                            }
                        }
                        else
                        {
                            //MessageBox.Show("電子表格信息有錯!");
                            errorcount++;
                        }
                    }
                    myRefresh();
                    MessageBox.Show(insertcount + "條數據導入成功!" + updatecount + "條數據重復!" + errorcount + "條數據部分信息為空沒有導入!");
                }
                catch (Exception ex)
                {
    
                    MessageBox.Show(ex.Message);
                }
    
                finally
                {
                    conn.Close();
    
                }
            }
    

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM