2017-10-13 1 views
0

Excel 시트의 특정 요소를 목록으로 가져 오는 방법을 찾고 있습니다. 내 목표는 Excel 시트의 속성 (첫 번째 행)을 정렬 (보고 싶은 속성을 클릭)하고 첫 번째 행 아래의 행 값을 가져 오는 것입니다.Excel 행 및 목록을 목록으로 가져 오기

+1

엑셀을 참조로 추가 했습니까? – BugFinder

+1

가능한 복제본 [ "using a using directive or assembly reference"및 어떤 잘못 될지 전혀 알지 못함] (https://stackoverflow.com/questions/17344295/im-getting-the-missing-a-using) -directive-or-assembly-reference-and-no-clue-wh) – SeM

+0

당신은'Excel.Sheets'을 쓸 필요가 없습니다. 당신은 이미'Excel' 지시어를 사용 했으므로 인터페이스 인'Sheet'를 작성하십시오. 그렇지 않으면 콘크리트 클래스 '워크 시트'를 사용할 수 있습니다. – praty

답변

0

나는 Sheet 인터페이스를 사용하지 않고이 방법으로 원하는 것을 구현하지만 Worksheet 클래스 개체를 사용합니다.

2 차원 어레이에서 사용 된 모든 범위를 얻은 후에 Excel 시트를 닫을 것입니다. 이렇게하면 읽기 속도가 훨씬 빨라지므로 범위에서 읽는 속도가 훨씬 느려집니다. 훨씬 더 빨리 만들 수있는 많은 방법이있을 수 있습니다.

Application xlApp = new Application(); 
Workbook xlWorkBook = null; 
Worksheet dataSheet = null; 
Range dataRange = null; 
List<string> columnNames = new List<string>(); 
object[,] valueArray; 

try 
{ 
    // Open the excel file 
    xlWorkBook = xlApp.Workbooks.Open(fileFullPath, 0, true); 

    if (xlWorkBook.Worksheets != null 
     && xlWorkBook.Worksheets.Count > 0) 
    { 
     // Get the first data sheet 
     dataSheet = xlWorkBook.Worksheets[1]; 

     // Get range of data in the worksheet 
     dataRange = dataSheet.UsedRange; 

     // Read all data from data range in the worksheet 
     valueArray = (object[,])dataRange.get_Value(XlRangeValueDataType.xlRangeValueDefault); 

     if (xlWorkBook != null) 
     { 
      // Close the workbook after job is done 
      xlWorkBook.Close(); 
      xlApp.Quit(); 
     } 

     for (int colIndex = 0; colIndex < valueArray.GetLength(1); colIndex++) 
     { 
      if (valueArray[0, colIndex] != null 
       && !string.IsNullOrEmpty(valueArray[0, colIndex].ToString())) 
      { 
       // Get name of all columns in the first sheet 
       columnNames.Add(valueArray[0, colIndex].ToString()); 
      } 
     } 
    } 

    // Now you have column names or to say first row values in this: 
    // columnNames - list of strings 
} 
catch (System.Exception generalException) 
{ 
    if (xlWorkBook != null) 
    { 
     // Close the workbook after job is done 
     xlWorkBook.Close(); 
     xlApp.Quit(); 
    } 
} 
+0

그건 정말 좋은 것입니다. 짧고 일치하는 솔루션 :) Thx 다시 도움을! – Niclas

+0

그래서 오늘 코드를 사용해 보았습니다. 프로그램이 catch() {} 전에 마지막 if() {}에 들어가기 때문에 예외가 발생합니다. 문제가 발생하지 않습니다. 나는 그것이 그 상태와 관련이 있다고 생각합니다. – Niclas

+0

@Niclas 예외 메시지는 무엇입니까? 'valueArray'가 비어 있기 때문일 수 있습니까? 디버그에서 'valueArray'에서 무엇을 볼 수 있습니까? – praty

관련 문제