728x90
1. 새프로젝트 생성
2. 만들어 져있는 cs 파일 이름 MainApp.cs로 변경
3. 종속성에 오른쪽 클릭 후 프로젝트 참조 추가
4. COM > 형식 라이브러리 > Microsoft Excel 15.0 (버전은 컴터마다 다름) 선택
5. 확인 후 추가된거 볼 수 있음
6. interop 형식에 예 로 되어있는지 확인
7. 코드 작성
using System;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace COMInterop
{
class MainApp
{
// 예전 방법
public static void OldWay(string[,] data, string savePath)
{
Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Add(Type.Missing); // Type.Missing 생략 가능
Excel.Worksheet worksheet = (Excel.Worksheet)excelApp.ActiveSheet;
try
{
for (int i = 0; i < data.GetLength(0); i++)
{
((Excel.Range)worksheet.Cells[i + 1, 1]).Value2 = data[i, 0]; // 첫 번째 열
((Excel.Range)worksheet.Cells[i + 1, 2]).Value2 = data[i, 1]; // 두 번째 열
}
worksheet.SaveAs(savePath + "\\jju-book-old.xlsx",
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
}
finally
{
excelApp.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(excelApp);
}
}
// 요즘 방법
public static void NewWay(string[,] data, string savePath)
{
Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Add();
Excel._Worksheet worksheet = (Excel._Worksheet)excelApp.ActiveSheet;
try
{
for (int i = 0; i < data.GetLength(0); i++)
{
worksheet.Cells[i + 1, 1] = data[i, 0]; // 첫 번째 열
worksheet.Cells[i + 1, 2] = data[i, 1]; // 두 번째 열
}
worksheet.SaveAs(savePath + "\\jju-book-dynamic.xlsx");
}
finally
{
excelApp.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(excelApp);
}
}
static void Main(string[] args)
{
string savePath = System.IO.Directory.GetCurrentDirectory();
string[,] array = new string[,]
{
{ "Receptionist", "2017" },
{ "English Teacher", "2020" },
{ "Human Resource", "2021" },
{ "Developer", "2023" }
};
Console.WriteLine("Creating Excel doc in old way...");
OldWay(array, savePath);
Console.WriteLine("Creating Excel doc in new way...");
NewWay(array, savePath);
}
}
}
구버전, 신버전 동시에 진행 후 코드 비교
8. F5 빌드
9. source\repos\COMInterop\bin\Debug\net8.0
해당 경로에 생성된 파일 확인!!

728x90
'C# 기초 공부' 카테고리의 다른 글
C# namespace에 아직도 {}가 되어있으시다면..? (2) | 2025.01.22 |
---|---|
[백준] C# 나는야 포켓몬 마스터 이다솜 (1) | 2024.10.20 |
[C#] 이진 트리 공부 (0) | 2024.10.07 |
[C#] KeyValuePair vs Dictionary 차이점 (1) | 2024.10.02 |
[C#] 자바에서 C#으로 변화하는 과정... Visual Studio 처음 쓰기 (2) | 2024.09.25 |