c# Excel에서 DataSet으로 이동

1584 단어 C#Exceldataset
#region  Excel DataSet
        public static DataSet ExcelToDataSet(string strFilePath,string type)
        {
            string strConn="";
            if (type == "excel2003")
            {
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
            }
            else if (type == "excel2007")
            {
                strConn = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + strFilePath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
            }
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });// Excel sheetname
            OleDbDataAdapter odda;
            DataSet ds = new DataSet();
            foreach (DataRow dr in sheetNames.Rows)
            {
                DataSet dsOne = new DataSet();
                odda = new OleDbDataAdapter("select * from [" + dr[2] + "]", strConn);//dr[2] is sheetname
                odda.Fill(dsOne);
                if (dsOne.Tables.Count > 0)
                {
                    DataTable dt = dsOne.Tables[0].Copy();
                    dt.TableName = dr[2].ToString();
                    ds.Tables.Add(dt);
                }
            }
            conn.Close();
            return ds;
        }
        #endregion 

좋은 웹페이지 즐겨찾기