c# 获取表格信息 并插入到数据库中

1、读取一个excel文件到DataSet集中

#region 读取一个excel文件到DataSet集中

        public static DataSet ExcelToDataSet(string filename)  //函数用来读取一个excel文件到DataSet集中  
        {
            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Extended Properties=Excel 8.0;" + "data source=" + filename;
            OleDbConnection myConn = new OleDbConnection(strCon);
            string strCom = " SELECT * FROM [Sheet1$]";     //"Sheet1"为表单标签页名  
            myConn.Open();
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
            DataSet ds;
            ds = new DataSet();
            myCommand.Fill(ds);
            myConn.Close();
            return ds;
        }

        #endregion

2、把指定表格中的信息插入到数据库中

         #region 把指定表格中的信息插入到数据库中

            using (var db = SugarHelper.GetInstance())
            {

                DataSet ds = ExcelToDataSet("E:\\111.xls");            //括号中为表格地址  
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string goods_no = ds.Tables[0].Rows[i]["商品编码"].ToString();
                    int num = ds.Tables[0].Rows[i]["数量"].ObjToInt();
                    string sql = "INSERT INTO `TEST` (`goods_no`, `num`) VALUES ( '" + goods_no + "', '" + num + "')";
                    db.ExecuteCommand(sql);
                }
            }
            #endregion

 

你可能感兴趣的:(VS)