존재하는 excel 파일에 데이터 가져오기


  
  
  
  
  1. CRUD  
  2.  
  3. using System;  
  4. using System.Collections;  
  5. using System.Collections.Generic;  
  6. using System.Text;  
  7. using System.Data;  
  8. using System.Data.OleDb;  
  9.  
  10.  
  11. namespace myexcel{  
  12.     public class DbExcel  
  13.     {  
  14.           
  15.         /// <summary> 
  16.         ///   
  17.         /// </summary> 
  18.         /// <param name="phyfilepath"></param> 
  19.         /// <returns></returns> 
  20.         private static string GetOptionConnstr(string phyfilepath)  
  21.         {  
  22.             string endstr = phyfilepath.Substring(phyfilepath.IndexOf('.') + 1);  
  23.             if (endstr.ToLower() == "xlsx")  
  24.             {  
  25.                 return "Provider=Microsoft.ACE.OleDb.12.0;Extended Properties=\"Excel 12.0;HDR=no;\";Data Source=" + phyfilepath;  
  26.             }  
  27.  
  28.             return "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=no;\";Data Source=" + phyfilepath;  
  29.         }  
  30.  
  31.  
  32.         /// <summary> 
  33.         ///   
  34.         /// </summary> 
  35.         /// <param name="phyfilepath"></param> 
  36.         /// <returns></returns> 
  37.         private static string GetReadConnStr(string phyfilepath)  
  38.         {  
  39.             string endstr = phyfilepath.Substring(phyfilepath.IndexOf('.') + 1);  
  40.             if (endstr.ToLower() == "xlsx")  
  41.             {  
  42.                 return "Provider=Microsoft.ACE.OleDb.12.0;Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1\";Data Source="+phyfilepath;   
  43.             }  
  44.      
  45.                 return "Provider=Microsoft.Jet." +  
  46.                 "OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";Data Source="+phyfilepath;                  
  47.         }  
  48.  
  49.  
  50.         public static DataTable GetExcelDataTable(string phyfilepath)  
  51.         {  
  52.             OleDbConnection conn = null;  
  53.             string sheetName = "Sheet1";  
  54.             DataTable dataTable = null;  
  55.               
  56.             try  
  57.             {  
  58.                 using (conn = new OleDbConnection(GetReadConnStr(phyfilepath)))  
  59.                 {  
  60.                     conn.Open();  
  61.                     DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  62.  
  63.                         foreach (DataRow dr in sheetNames.Rows)  
  64.                         {  
  65.                             sheetName = dr[2].ToString().Trim();  
  66.                             break;  
  67.                         }  
  68.                     OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);  
  69.                     DataSet ds = new DataSet();  
  70.                     oada.Fill(ds, "InitData");  
  71.  
  72.                     dataTable = ds.Tables["InitData"];  
  73.                 }  
  74.             }  
  75.             catch (Exception ex)  
  76.             {  
  77.                 throw new BaseDBException(ex.Message);  
  78.             }  
  79.             finally  
  80.             {  
  81.                 conn.Close();  
  82.             }  
  83.  
  84.             return dataTable;  
  85.         }  
  86.  
  87.         public static DataTable GetExcelSheetTable(string phyfilepath)  
  88.         {  
  89.             OleDbConnection conn = null;  
  90.             string sheetName = "Sheet1$";  
  91.             DataTable dataTable = null;  
  92.  
  93.             try  
  94.             {  
  95.                 using (conn = new OleDbConnection(GetReadConnStr(phyfilepath)))  
  96.                 {  
  97.                     conn.Open();  
  98.                     OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);  
  99.                     DataSet ds = new DataSet();  
  100.                     oada.Fill(ds, "InitData");  
  101.  
  102.                     dataTable = ds.Tables["InitData"];  
  103.                 }  
  104.             }  
  105.             catch (Exception ex)  
  106.             {  
  107.                 throw new BaseDBException(ex.Message);  
  108.                 //return null;  
  109.                 
  110.             }  
  111.             finally  
  112.             {  
  113.                 conn.Close();  
  114.             }  
  115.  
  116.             return dataTable;  
  117.         }  
  118.  
  119.         public static DataTable GetExcelSheetTable(string phyfilepath,string SheetName)  
  120.         {  
  121.             OleDbConnection conn = null;  
  122.             string sheetName = SheetName;  
  123.             DataTable dataTable = null;  
  124.  
  125.             try  
  126.             {  
  127.                 using (conn = new OleDbConnection(GetReadConnStr(phyfilepath)))  
  128.                 {  
  129.                     conn.Open();  
  130.                     DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  131.  
  132.  
  133.                     OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);  
  134.                     DataSet ds = new DataSet();  
  135.                     oada.Fill(ds, "InitData");  
  136.  
  137.                     dataTable = ds.Tables["InitData"];  
  138.                 }  
  139.             }  
  140.             catch (Exception ex)  
  141.             {  
  142.                 throw new BaseDBException(ex.Message);  
  143.             }  
  144.             finally  
  145.             {  
  146.                 conn.Close();  
  147.             }  
  148.  
  149.             return dataTable;  
  150.         }  
  151.           
  152.         public static void ExcelColDataUpdate(string phyfilepath, string sheetName,string setvalue,string where)  
  153.         {  
  154.             OleDbConnection conn = null;  
  155.             try  
  156.             {  
  157.                 using (conn = new OleDbConnection(GetOptionConnstr(phyfilepath)))  
  158.                 {  
  159.                     conn.Open();  
  160.                     OleDbCommand cmd = new OleDbCommand();  
  161.                     cmd.CommandType = CommandType.Text;  
  162.  
  163.                     cmd.CommandText = "UPDATE ["+sheetName+"$] "+setvalue+" "+where;  
  164.                     cmd.Connection = conn;  
  165.                     cmd.ExecuteNonQuery();  
  166.  
  167.                 }  
  168.             }  
  169.             catch (Exception ex)  
  170.             {  
  171.                 throw new BaseDBException(ex.Message);  
  172.             }  
  173.             finally  
  174.             {  
  175.                 conn.Close();  
  176.             }  
  177.           
  178.           
  179.         }  
  180.  
  181.         public static void ExcelColDataInsert(string phyfilepath, string sheetName, string columnNames, string values)  
  182.         {  
  183.             OleDbConnection conn = null;  
  184.             try  
  185.             {  
  186.                 using (conn = new OleDbConnection(GetOptionConnstr(phyfilepath)))  
  187.                 {  
  188.                     conn.Open();  
  189.                     OleDbCommand cmd = new OleDbCommand();  
  190.                     cmd.CommandType = CommandType.Text;  
  191.  
  192.                     cmd.CommandText = "insert into [" + sheetName + "$] (" + columnNames + ") values(" + values + ")";  
  193.                     cmd.Connection = conn;  
  194.                     cmd.ExecuteNonQuery();  
  195.                       
  196.                 }  
  197.             }  
  198.             catch (Exception ex)  
  199.             {  
  200.                 throw new BaseDBException(ex.Message);  
  201.             }  
  202.             finally  
  203.             {  
  204.                 conn.Close();  
  205.             }  
  206.           
  207.         }  
  208.  
  209.         public static void ExcelVoucherDataInsert(string filePath, string sheetName, DataTable dt)  
  210.         {  
  211.             StringBuilder sb = new StringBuilder();  
  212.             if (dt == null || dt.Rows.Count == 0) return;  
  213.             try  
  214.             {  
  215.                 using (OleDbConnection conn = new OleDbConnection(GetOptionConnstr(filePath)))  
  216.                 {  
  217.                     conn.Open();  
  218.                     foreach (DataRow row in dt.Rows)  
  219.                     {  
  220.                         OleDbCommand cmd = new OleDbCommand();  
  221.                         cmd.CommandType = CommandType.Text;  
  222.                         cmd.CommandText = "insert into [" + sheetName + "$] values('" + row["FName"].ToString() + "','" + row["FNo"].ToString() + "','" + row["FIName"].ToString() + "')";  
  223.                         cmd.Connection = conn;  
  224.                         cmd.ExecuteNonQuery();  
  225.                     }  
  226.                 }  
  227.             }  
  228.             catch (Exception ex)  
  229.             {  
  230.                 throw new BaseDBException(ex.Message);  
  231.             }  
  232.         }  
  233.  
  234.         public static void  ExcelVoucherDataInsert(string filePath, string sheetName, string itemClass , string number , string name)  
  235.         {  
  236.             try  
  237.             {  
  238.                 using (OleDbConnection conn = new OleDbConnection(GetOptionConnstr(filePath)))  
  239.                 {  
  240.                     conn.Open();  
  241.                     OleDbCommand cmd = new OleDbCommand();  
  242.                     cmd.CommandType = CommandType.Text;  
  243.  
  244.                     cmd.CommandText = "insert into [" + sheetName + "$] values('" + itemClass + "','" + number + "','" + name + "')";  
  245.                     cmd.Connection = conn;  
  246.                     cmd.ExecuteNonQuery();  
  247.                 }  
  248.             }  
  249.             catch(Exception ex)  
  250.             {  
  251.                 throw new BaseDBException(ex.Message);  
  252.             }  
  253.         }  
  254.           
  255.  
  256.         public static void ExcelColDataInsert(string phyfilepath, string sheetName, string columnName, string[] values)  
  257.         {  
  258.             OleDbConnection conn = null;  
  259.             try  
  260.             {  
  261.                 using (conn = new OleDbConnection(GetOptionConnstr(phyfilepath)))  
  262.                 {  
  263.                     conn.Open();  
  264.                     OleDbCommand cmd = new OleDbCommand();  
  265.                     cmd.CommandType = CommandType.Text;  
  266.  
  267.                     foreach (string str in values)  
  268.                     {  
  269.                         cmd.CommandText = "insert into [" + sheetName + "$] (" + columnName + ") values(' " + str + "')";  
  270.                         cmd.Connection = conn;  
  271.                         cmd.ExecuteNonQuery();  
  272.                     }  
  273.                 }  
  274.             }  
  275.             catch (Exception ex)  
  276.             {  
  277.                 throw new BaseDBException(ex.Message);  
  278.             }  
  279.             finally  
  280.             {  
  281.                 conn.Close();  
  282.             }  
  283.         }  
  284.       
  285.     }  
  286.  

excel 파일을 연결하고 조작하는 공통 함수 작성

  
  
  
  
  1.  
  2.  
  3. protected void DoOleSql(string sql, string database)  
  4.  
  5.   {     
  6.  
  7.   OleDbConnection conn = new OleDbConnection();  
  8.  
  9.   conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("\\") + database + "; Extended Properties='Excel 8.0;HDR=no;IMEX=0'";  
  10.  
  11.   try  
  12.  
  13.   {//  
  14.  
  15.   conn.Open();  
  16.  
  17.   }  
  18.  
  19.   catch (Exception e)  
  20.  
  21.   {  
  22.  
  23.   Response.Write(e.ToString());  
  24.  
  25.   }  
  26.  
  27.   OleDbCommand olecommand = new OleDbCommand(sql, conn);     
  28.  
  29.   try  
  30.  
  31.   {//  
  32.  
  33.   olecommand.ExecuteNonQuery();  
  34.  
  35.   }  
  36.  
  37.   catch (Exception eee)  
  38.  
  39.   {  
  40.  
  41.   Response.Write(eee.ToString());  
  42.  
  43.   conn.Close();  
  44.  
  45.   }  
  46.  
  47.   finally  
  48.  
  49.   {  
  50.  
  51.   conn.Close();//  
  52.  
  53.   }  
  54.  
  55.   conn.Close();  
  56.  

참고: 1) Excel 워크북을 사용할 때 기본적으로 영역의 첫 번째 줄은 제목 줄 (또는 필드 이름) 입니다.첫 번째 영역에 제목이 없으면 연결 문자열의 확장 속성에 HDR=NO를 지정할 수 있습니다.연결 문자열에 HDR=NO를 지정하면 Jet OLE DB 공급자가 자동으로 필드를 지정합니다(F1은 첫 번째 필드를 나타내고 F2는 두 번째 필드를 나타냅니다).2) IMEX=1 읽은 모든 데이터를 문자로 간주하고 다른 값(0, 2)은 관련 도움말 문서를 참조하십시오.3) "설치할 수 있는 isam을 찾을 수 없습니다"오류가 발생하면 연결 문자열 오류 3, excel 파일에서 데이터 읽기string sql = "select * from [sheet1$]"DoOleSql(sql,"test.xls"); 4. excel 파일의 데이터string sql ='update [sheet1$] set FieldName1='333'where FieldName2='b3'를 업데이트합니다.DoOleSql(sql,"test.xls"); 5. excel 파일에 데이터string sql = "insert into [sheet1$](FieldName1, FieldName2,...)values('a','b','...)";DoOleSql(sql,"test.xls"); 6. excel 파일의 데이터 삭제: 이런 방법을 사용하지 않습니다. 7. 비표준 구조의 excel 표에 대해 excel의 sheet의 범위를 지정할 수 있습니다. 1) 데이터 읽기:string sql ="select* from [sheet1$A3:F20]"2) 업데이트 데이터:string sql ='update [sheet1$A9:F15] set FieldName='333'where AnotherFieldName='b3';3) 데이터 삽입:string sql ='insert into [sheet1$A9:F15](FieldName1, FieldName2,...)values('a','b','...)';4) 데이터 삭제: 주: 1) 코드는 필요에 따라 스스로 수정할 수 있다.2) "업데이트할 수 있는 조회를 사용해야 합니다."오류가 발생하면 sql 문장에서 excel 파일의 "필드"인용에 오류가 있거나 excel 파일에 "수정"권한이 없을 수 있습니다.3) "선택한 범위를 확장할 수 없습니다"오류가 발생하면 excel 파일에 인용된'범위'에 오류가 있을 수 있습니다.

좋은 웹페이지 즐겨찾기