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(); // 가비지 수집
}
}
}
}
ReleaseObject(object obj) : 엑셀 객체를 사용하고 난 후 반드시 엑셀 객체를 해제(Release)해 주어야 합니다.
workSheet.Cells[row, column]를 사용할 경우 row, column의 인덱스는 0이 아닌 1부터 시작해야 합니다.