C# 응용) 엑셀 불러오기

guk (Guk)·2021년 10월 29일
0

C Sharp-Applications

목록 보기
1/2
post-thumbnail

1.엑셀 연결하기 위한 준비.

  • 먼저 Microsoft Excel Object Library를 참조로 추가한다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;//추가 1
using System.Runtime.InteropServices;//추가 2
using System.IO;//추가 3

namespace ConsoleApp_study
{

    class study1
    {
        static Excel.Application excelApp = null; 
        static Excel.Workbook workBook = null; 
        static Excel.Worksheet workSheet = null; 
        
        static void Main(string[] args)
        {

            try
            {
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // 바탕화면으로 경로 설정
                string path = Path.Combine(desktopPath, "FILE.xlsx"); // 엑셀 파일 저장 경로 및 파일 명칭 설정
                excelApp = new Excel.Application(); // 엑셀 어플리케이션 생성
                workBook = excelApp.Workbooks.Open(path); // 워크북 열기
                workSheet = workBook.Worksheets.get_Item(1) as Excel.Worksheet; // 엑셀 첫번째 워크시트 가져오기
                Excel.Range range = workSheet.UsedRange; // 사용중인 셀 범위를 가져오기

                for (int row = 4; row <= range.Rows.Count; row++) // 가져온 열 만큼 반복 세로
                {
                    for (int column = 2; column <= 9; column++) // 가져온 행 만큼 반복 가로
                    {
                  	string excelValue; //엑셀의 값을 저장하기 위한 변수
                        excelValue = Convert.ToString((range.Cells[row, column]).Value2);
                    }
                }
                workBook.Close(true); // 워크북 닫기
                excelApp.Quit(); // 엑셀 어플리케이션 종료
            } 
            finally 
            {   ReleaseObject(workSheet); //객체 해제 메소드
                ReleaseObject(workBook); //객체 해제 메소드
                ReleaseObject(excelApp); //객체 해제 메소드
            } 
        } 
        
        static void ReleaseObject(object obj)// 액셀 객체 해제 메소드 
        { 
            try 
            { 
                if (obj != null) 
                { 
                    Marshal.ReleaseComObject(obj); // 액셀 객체 해제
                    obj = null; 
                } 
            } catch (Exception ex) 
            { 
                obj = null; 
                throw ex; 
            } finally 
            { 
                GC.Collect(); // 가비지 수집
            } 
        } 
    }
}
  • 셀 가져오기
    workSheet.Ceels[5,1] -> A5셀 가져옴
  • 여러 셀 가져오기
    workSheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, 3]] : A1부터 C1까지의 셀을 가져옴workSheet.Range[“A2 : C2”] : A2부터 C2까지의 셀을 가져옴 (엑셀 표현 그대로 사용가능)
  • 식 또는 값 가져오기
    worksheet.Cells[3,3].Value2 : 셀의 식 또는 값을 가져옴
  • 수식 가져오기
    worksheet.Cells[3,3].Fomula : 셀의 수식 가져옴

ReleaseObject(object obj) : 엑셀 객체를 사용하고 난 후 반드시 엑셀 객체를 해제(Release)해 주어야 합니다.

workSheet.Cells[row, column]를 사용할 경우 row, column의 인덱스는 0이 아닌 1부터 시작해야 합니다.

profile
개발자 블로그 및 이것저것

0개의 댓글