2014-11-15 4 views
0

Excel 스프레드 시트를 데이터 배열 배열로 가져 오려고합니다. 각 표는 스프레드 시트의 시트가됩니다. 지금은 각 테이블에 모든 시트의 정보가 포함되어 있습니다. 이 부분이 올바르게 작동하지 않는다고 생각합니다.Excel 시트를 여러 C# 데이터 테이블로 변환

dataSet.Clear(); 

제가 잘못하고있는 것을 볼 수 있는지 알려주세요.

다음은 나머지 코드입니다.

 public DataTable[] ReadDoc() 
     { 
     string filename = @"C:\Documents and Settings\user\Desktop\Test.xlsx"; 
     DataTable dt = null; 

     string connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\";", filename); 
     OleDbConnection connection = new OleDbConnection(connectionString); 

     DataSet dataSet = new DataSet(); 
     DataSet finalDataSet = new DataSet(); 
     DataTable[] table = new DataTable[3]; 
     connection.Open(); 

     dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 

     if (dt == null) 
     { 
      return null; 
     } 

     String[] excelSheets = new String[dt.Rows.Count]; 
     int i = 0; 

     foreach (DataRow row in dt.Rows) 
     { 
      excelSheets[i] = row["TABLE_NAME"].ToString(); 
      i++; 
     } 

     // Loop through all of the sheets if you want too... 
     for (int j = 0; j < excelSheets.Length; j++) 
     { 
      string query = String.Format("SELECT * FROM [" + excelSheets[j] + "]"); 
      dataSet.Clear(); 
      OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString); 
      dataAdapter.Fill(dataSet); 
      table[j] = dataSet.Tables[0]; 
     } 

     return table; 
     } 

감사합니다.

답변

1

여기의 문제는 데이터 세트이며, outsife라고 선언되었습니다. 각 datatable 배열 항목은 동일한 정보를 얻고 있습니다. dataSet.Tables [0]; for에 선언해야합니다. 각 반복에는 서로 다른 정보가 저장됩니다.

for (int j = 0; j < excelSheets.Length; j++) 
    { 
     DataSet dataSet = new DataSet(); 
     string query = String.Format("SELECT * FROM [" + excelSheets[j] + "]"); 
     ..... 
    } 
관련 문제