! 제품 버전을 정확하게 입력해 주세요.
제품 버전이 정확하게 기재되어 있지 않은 경우,
최신 버전을 기준으로 안내 드리므로
더욱 빠르고 명확한 안내를 위해
제품 버전을 정확하게 입력해 주세요!

C#을 사용하여 Excel 파일에서 시트와 범위를 가져오는 방법 > 온라인 스터디

본문 바로가기

C#을 사용하여 Excel 파일에서 시트와 범위를 가져오는 방법

페이지 정보

작성자 GrapeCity 작성일 2022-06-10 14:20 조회 1,392회 댓글 0건

본문

첨부파일

Grapecity Documents for Excel( Java 에디션 | .NET 에디션 )에는 이제 기능이 풍부한 API에 또 다른 강력한 기능인 ImportData를 포함할 수 있습니다.



이름으로 알 수 있듯이 이 기능은 Excel 파일에서 데이터를 가져옵니다. 여기서 생기는 궁금증은 이 기능이 Excel 파일을 GcExcel로 로드하는 데 사용되는 Open 메서드와 어떤 점에서 다른가입니다. 


두 기능 사이의 차이점을 자세히 살펴보면서 각 기능을 언제 사용하는 것이 가장 적절한지 알아보겠습니다.


Open 함수ImportData 함수
Excel 개체 모델을 로드합니다.Excel 개체 모델을 로드하지 않습니다.
스프레드시트를 열고 값과 수식을 포함하여 모든 데이터 유형을 로드합니다.스프레드시트를 열고 데이터만 가져옵니다.
수식이 로드되면 CalcEngine이 작동합니다.CalcEngine은 개체 모델 없이 작동할 수 없습니다. 따라서 수식이 무시됩니다.
전체 개체 모델을 로드해야 하기 때문에 비교적 시간이 더 걸립니다.개체 모델을 로드하지 않고 데이터만 가져오기 때문에 훨씬 더 빠릅니다.


위 차이점은 데이터가 데이터 요소인 경우 ImportData 함수가 Excel 파일에서 데이터를 가져오는 데 훨씬 빠른 방법임을 확실하게 보여 줍니다. 그러나 함수와 계산을 가져와야 하는 경우에는 Open 함수가 더 나은 선택입니다.


이 블로그에서는 ImportData 함수의 구문 및 기능을 설명하고 보여주며 OpenImportData 간 속도 차이를 확인할 수 있는 타임 트라이얼 데이터를 제공합니다. 이 게시글을 통해 이러한 함수에 대해 더 잘 이해하게 되고 고유한 사용 사례 또는 필요에 따라 적합한 함수를 결정할 수 있습니다.



ImportData 함수


ImportData 함수는 지정된 소스에서 모든 데이터를 가져오고, 소스는 통합 문서 내 워크시트, 표 또는 셀 범위를 참조할 수 있습니다. 소스에서 가져온 데이터는 ImportData 메서드에 의해 배열로 반환됩니다.


이 정적 함수의 기본 구문은 다음과 같습니다.


지정된 소스의 모든 데이터 가져오기:

public static System.object[,] ImportData(System.string fileName, System.string sourceName)


이 메서드의 첫 번째 매개 변수는 통합 문서 이름을 수락하고, 두 번째 매개 변수는 통합 문서의 워크시트 이름, 표 이름 또는 셀 범위를 수락합니다.


사용자가 유효한 시트 이름 또는 표 이름을 알고 있는 경우 해당 이름을 직접 전달할 수 있습니다.


그러나 사용자가 이름을 잘 모르는 경우에는 GcExcel API의 또 다른 메서드인 GetNames를 사용할 수 있습니다.


Workbook 클래스의 정적 메서드인 GetNames는 통합 문서 이름 또는 스트림을 매개 변수로 수락하여 통합 문서의 모든 시트 이름과 표 이름을 반환합니다.


이름이 표 이름인 경우 워크시트 이름은 표 이름 앞에서 정규화됩니다(예: "Sheet1!Table1").

워크시트 이름에 특수 문자(예: ''', '!' ,' ')가 포함된 경우 워크시트 이름은 작은따옴표로 묶습니다 (예: "'Sheet!1'!Table1").


이 메서드가 반환하는 이름은 ImportData 메서드의 소스 매개 변수에 사용할 수 있습니다.


아래 코드 조각은 ImportDataGetNames 메서드를 모두 사용하여 통합 문서의 표에서 데이터를 모두 검색하는 방법을 설명합니다.

//create a new workbook
var workbook = new GrapeCity.Documents.Excel.Workbook();

// Open an excel file
var fileStream = GetResourceStream("xlsx\\AgingReport.xlsx");

// Get the possible import names in the file.
// The names[0] and names[1] are sheet names: "Aging Report", "Invoices".
// The names[2] and names[3] are table names: "'Aging Report'!tblAging", "Invoices!tblInvoices".
var names = GrapeCity.Documents.Excel.Workbook.GetNames(fileStream);

// Import the data of a table "'Aging Report'!tblAging" from the fileStream.
var data = GrapeCity.Documents.Excel.Workbook.ImportData(fileStream, names[2]);

// Assign the data to current workbook.
workbook.Worksheets[0].Range[0, 0, data.GetLength(0), data.GetLength(1)].Value = data;

// Save to an excel file
workbook.Save("importdatafortable.xlsx");


이러한 메서드의 구현 및 작동에 대해 숙지하려면 데모를 다운로드하십시오.


ImportData 함수의 또 다른 오버로드는 지정된 워크시트의 특정 셀 범위에서 데이터를 가져오는 것입니다.

public static System.object[,] ImportData(
  System.string fileName,
  System.string worksheetName,
  System.int row,
  System.int column,
  System.int rowCount,
  System.int columnCount
)


ImportData 메서드의 모든 오버로드를 살펴보려면 다음 문서를 참조하십시오.



사용 사례: C# .NET을 사용하여 처리 속도 비교


속도 차이를 테스트하기 위해 OpenImportData 메서드를 모두 사용하여 많은 수식이 포함된 통합 문서 로드를 구현하는 것을 살펴보겠습니다.


Open 메서드를 사용하여 통합 문서를 로드하는 데 소요되는 시간을 측정할 때 프로세스를 완료하는 데 11ms 가까이 걸린 것으로 관찰되었습니다.


그러나 ImportData 메서드를 사용한 경우에는 같은 작업을 완료하는 데 4ms가 걸렸습니다. 따라서 Open 대신 ImportData 함수를 사용하면 코드가 얼마나 효율적인지 알 수 있습니다.


아래 단계에서는 ImportData 함수와 Open 함수를 사용하여 많은 수식이 포함된 통합 문서에서 데이터를 로드하는 방법을 설명합니다.


  1. 새로운 C#용 .NET Core 콘솔 응용 프로그램을 만듭니다.

  2. Nuget 패키지 관리자를 사용하여 Grapecity Documents for Excel v5.1 패키지를 설치합니다. NuGet 솔루션

  3. ImportData 함수와 Open 함수를 모두 사용하여 많은 수식이 포함된 통합 문서에서 데이터를 가져오고 반환된 데이터를 각 통합 문서에 로드하는 다음 메서드를 추가합니다. 나중에 성능 결과를 보여 주기 위해 두 메서드를 사용하여 데이터를 로드하는 데 걸린 시간을 Excel 파일로 저장된 통합 문서에 추가합니다.


코드 주석에서는 새 통합 문서를 만든 방법, ImportData 함수와 Open 함수를 사용하여 데이터를 가져온 방법, 가져온 데이터로 통합 문서를 채운 방법을 설명합니다.


static void TestPerformance()
{
  //create a new workbook
  var workbook = new GrapeCity.Documents.Excel.Workbook();

  workbook.ActiveSheet.Range["A:B"].ColumnWidth = 35;
  workbook.ActiveSheet.Range["A2:B2"].HorizontalAlignment = HorizontalAlignment.Right;

  //Number of times to read data.
  int count = 10;

  #region ImportData
  //Create a new workbook.        
  var importDataWorkbook = new GrapeCity.Documents.Excel.Workbook();
  importDataWorkbook.Worksheets.Add();

  //Total time consumed to import data "count-2" times.
  long importDataTotalTimeConsumed = 0;

  for (int i = 0; i < count; i++)
  {
     var importDataFileStream = GetResourceStream("xlsx\\AgingReport1.xlsx");

     //Start time to read Excel data.
     var importDatasw = new System.Diagnostics.Stopwatch();
     importDatasw.Start();

     //Import data of the range from the fileStream.              
     var data1 = GrapeCity.Documents.Excel.Workbook.ImportData(importDataFileStream, "Aging Report");
     var data2 = GrapeCity.Documents.Excel.Workbook.ImportData(importDataFileStream, "Invoices");            

     //End time to read Excel data.
     importDatasw.Stop();

     // Assign the data to current workbook
     importDataWorkbook.Worksheets[0].Range[0, 0, data1.GetLength(0), data1.GetLength(1)].Value = data1;
     importDataWorkbook.Worksheets[1].Range[0, 0, data2.GetLength(0), data2.GetLength(1)].Value = data2;    
     
     //The operating system has a cache to open the file, and it takes time to open the file for the first time.
     //For the accuracy of statistics, the time of the first and last time is removed.
     if (i > 0 && i < count - 1)
    {
         importDataTotalTimeConsumed += importDatasw.ElapsedMilliseconds;
    }
  }

  //Average time consumed to read data using "importData" method.
  double importDataTimeConsumed = (double)importDataTotalTimeConsumed / (count - 2);

  //Save to an excel file.
  importDataWorkbook.Save("Data1.xlsx");
  #endregion

  #region Open
  //Create a new workbook.
  var openWorkbook = new GrapeCity.Documents.Excel.Workbook();

  //Total time consumed to open Excel file "count-2" times.
  long openTotalTimeConsumed = 0;

  for (int i = 0; i < count; i++)
  {
      var openFileStream = GetResourceStream("xlsx\\AgingReport1.xlsx");

      //Start time to read Excel data.
      var opensw = new System.Diagnostics.Stopwatch();
      opensw.Start();

      //Import Excel data using "Open" Method.
      openWorkbook.Open(openFileStream);

      //End time to read Excel data.
      opensw.Stop();

      //The operating system has a cache to open the file, and it takes time to open the file for the first time.
      //For the accuracy of statistics, the time of the first and last time is removed.
      if (i > 0 && i < count - 1)
      {
          openTotalTimeConsumed += opensw.ElapsedMilliseconds;
      }
  }

   //Average time consumed to import Excel data using "Open" method.
   double openTimeConsumed = (double)openTotalTimeConsumed / (count - 2);

   //Save to an excel file
   openWorkbook.Save("Data2.xlsx");

   #endregion

   workbook.ActiveSheet.Range["A1"].Value = "Time consumed by ImportData method";
   workbook.ActiveSheet.Range["B1"].Value = "Time consumed by Open method";

   //Store the time information of ImportData mehod in cell A2.
   workbook.ActiveSheet.Range["A2"].Value = importDataTimeConsumed.ToString() + "ms";

   //Store the time information of Open mehod in cell B2.
   workbook.ActiveSheet.Range["B2"].Value = openTimeConsumed.ToString() + "ms";

   // Save to an excel file
   workbook.Save("importdataforrange.xlsx");
}


위 단계를 구현하는 샘플을 다운로드하십시오. 이 샘플을 실행하면 시간 차이와 결과를 살펴볼 수 있습니다. 또한 여기에서 성능 샘플 데모를 확인할 수도 있습니다.


참고: 처리 속도는 시스템 설정 및 리소스에 따라 달라집니다.


Grapecity Documents for Excel에서 제공하는 다른 흥미로운 기능을 살펴보려면 데모문서를 참조하십시오.





지금 바로 GcExcel .NET Core를 다운로드하여 직접 테스트해보세요!

 
  • 페이스북으로 공유
  • 트위터로  공유
  • 링크 복사
  • 카카오톡으로 보내기

댓글목록

등록된 댓글이 없습니다.

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기

태그1

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기
이메일 : sales-kor@mescius.com | 전화 : 1670-0583 | 경기도 과천시 과천대로 7길 33, 디테크타워 B동 1107호 메시어스(주) 대표자 : 허경명 | 사업자등록번호 : 123-84-00981 | 통신판매업신고번호 : 2013-경기안양-00331 ⓒ 2024 MESCIUS inc. All rights reserved.