Computer
[C#] Excel 파일을 DataTable에 담기
창천(蒼天)
2014. 1. 28. 09:06
한꺼번에 많은 데이터를 DataTable 혹은 DataSet으로 옮길 때 유용하다.
private DataTable GetSheet(string FilePath) { string oledbConnectionString = string.Empty; if (FilePath.IndexOf(".xlsx") > -1) { //엑셀 2007 oledbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0\""; } else { //엑셀 2003 및 이하 버전 oledbConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0\""; } DataTable dt_Result = null; OleDbDataAdapter adt = null; using (OleDbConnection con = new OleDbConnection(oledbConnectionString)) { con.Open(); DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string sheetName = dt.Rows[0]["TABLE_NAME"].ToString(); //엑셀 첫 번째 시트명 string sQuery = string.Format(" SELECT * FROM [{0}] ", sheetName); //쿼리 dt_Result = new DataTable(); adt = new OleDbDataAdapter(sQuery, con); adt.Fill(dt_Result); } return dt_Result; }
FilePath : Excel 파일의 전체 경로
출처 : http://scanf.tistory.com/category/.NET/C%23