IT/C#

[C#] Excel 사용하기. Create Excel File + Update Excel File

Ella.J 2024. 3. 27. 16:11
728x90
반응형

 

[ C# Excel 사용하기 ]

 

1. 참조 추가하기

 

References > Add Reference... 클릭
COM > Microsoft Excel 12.0 Object Library 체크 후 OK 버튼 클릭

* 해당 PC에 Excel이 설치되어 있어야 하며, 엑셀 버전에 따라 해당 숫자가 다를 수 있음.

 

추가가 완료되면 참조에 Microsoft.Office.Interop.Excel이 추가된다.

 

2. Excel 사용하기

 

Excel.Application을 사용해야 하는데, 위와 같이 에러가 나온다면,

 

빠른 수정 옵션으로 위와 같이 길게 참조명을 적어줘도 되지만,

 

using Excel = Microsoft.Office.Interop.Excel; 과 같이 using 구문을 사용하여 간단하게 사용할 수도 있다.

 

3. 전체 소스코드

ExcelDataOutput.cs 파일을 생성하여 엑셀파일 생성과 업데이트를 해준다. (주석 참고)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
using System;
using System.IO;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
 
namespace ExcelFileSave
{
    class ExcelDataOutput
    {
        static Excel.Application excelApp = null;
        static Excel.Workbook wb = null;
        static Excel._Worksheet ws = null;
 
        public static string[] sColumnHeader = 
            { "[No.]""[Name]""[Birth]""[Phone]""[Address]" };
 
        public static bool CreateExcelFile(string sFilePath)
        {
            try
            {
                if (File.Exists(sFilePath))
                {
                    MessageBox.Show($"해당파일이 이미 존재합니다.");
                } else
                {
                    // 1. ExcelApp 연결
                    excelApp = new Excel.Application();
                    if (excelApp == null)
                    {
                        return false;
                    }
 
                    // 2. Workbook 생성
                    wb = excelApp.Workbooks.Add();
 
                    // 3. WorkSheet 생성
                    Excel.Worksheet infoSheet = (Excel.Worksheet)wb.Sheets.Add();
                    infoSheet.Name = "Info";
 
                    // 4. 자동 생성 되는 sheet1 제거
                    Excel.Worksheet sheet1 = null;
                    for (int i = 1; i <= wb.Sheets.Count; i++)
                    {
                        sheet1 = (Excel.Worksheet)wb.Sheets[i];
                        if (sheet1.Name == "Sheet1"// 찾고자 하는 시트의 이름
                        {
                            if (sheet1 != null// 시트를 찾았는지 확인
                            {
                                sheet1.Delete(); // 시트 삭제
                                break;
                            }
                        }
                    }
 
                    // 5. Workbook 저장하고 닫기
                    // (참고) 덮어쓰기 경고 알람창 없애기
                    excelApp.DisplayAlerts = false;
                    wb.SaveAs(sFilePath, Excel.XlFileFormat.xlWorkbookDefault);
                    wb.Close(Type.Missing, Type.Missing, Type.Missing);
 
                    // 6. ExcelApp 종료
                    excelApp.Quit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"엑셀파일 저장 에러.");
                return false;
            }
            finally
            {
                releaseObject(excelApp);
                releaseObject(ws);
                releaseObject(wb);
            }
 
            return true;
        }
 
        public static bool UpdateExcelFile(string sFilePath, string[,] Data)
        {
            try
            {
                if (!File.Exists(sFilePath))
                {
                    MessageBox.Show($"해당파일이 존재하지 않습니다.");
                }
                else
                {
                    // 1. ExcelApp 연결
                    excelApp = new Excel.Application();
                    if (excelApp == null)
                    {
                        return false;
                    }
 
                    // 2. Workbook 열기
                    wb = excelApp.Workbooks.Open(sFilePath);
 
                    // 3. Info WorkSheet 있는지 확인
                    int sheetNo = 1;
                    bool chkSheet = false;
                    Excel.Worksheet infoSheet = null;
                    for (int i = 1; i <= wb.Sheets.Count; i++)
                    {
                        infoSheet = (Excel.Worksheet)wb.Sheets[i];
                        if (infoSheet.Name == "Info"// 찾고자 하는 시트의 이름
                        {
                            if (infoSheet != null// 시트를 찾은 경우
                            {
                                sheetNo = i;
                                chkSheet = true;
                                break;
                            }
                        }
                    }
                    if (!chkSheet) // 해당 시트를 못 찾았을 경우 새로 생성
                    {
                        sheetNo = wb.Sheets.Count + 1;
                        // 현재 Workbook의 맨 마지막에 Worksheet 추가
                        infoSheet = (Excel.Worksheet)wb.Sheets.Add(After: wb.Sheets[wb.Sheets.Count]);
                        infoSheet.Name = "Info";
                    }
 
                    // 4. 데이터 넣기
                    // 1) 해당 Cell 값에 일일이 넣는 방법
                    for (int i = 0; i < sColumnHeader.Length; i++)
                    {
                        infoSheet.Cells[1, i + 1= sColumnHeader[i];
                        //[No.] | [Name] | [Birth] | [Phone] | [Address]
                    }
                    // 2) Data 길이만큼 Cell 범위 지정하여 넣는 방법
                    SheetSave(sheetNo, 12, Data);
 
                    // 5. Workbook 저장하고 닫기
                    // (참고) 덮어쓰기 경고 알람창 없애기
                    excelApp.DisplayAlerts = false;
                    wb.SaveAs(sFilePath, Excel.XlFileFormat.xlWorkbookDefault);
                    wb.Close(Type.Missing, Type.Missing, Type.Missing);
 
                    // 6. ExcelApp 종료
                    excelApp.Quit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"엑셀파일 저장 에러.");
                return false;
            }
            finally
            {
                releaseObject(excelApp);
                releaseObject(ws);
                releaseObject(wb);
            }
 
            return true;
        }
 
        public static bool SheetSave(int SheetIndex, int StartColumn, int StartRow, string[,] SheetData)
        {
            try
            {
                // Data 길이 체크 : i = 행개수, j = 열개수
                int i = SheetData.GetUpperBound(0+ 1;
                int j = SheetData.GetUpperBound(1+ 1;
 
                wb.Worksheets[SheetIndex].select();
                ws = wb.ActiveSheet;
                // 시작열(ex. A2)부터 체크한 Data 길이의 행열의 값에 SheetData를 넣음
                ws.Range[StartCellCheck(StartColumn, StartRow)].Resize[i, j].Value = SheetData;
            }
            catch
            {
                return false;
            }
 
            return true;
        }
 
        public static string StartCellCheck(int StartColumn, int StartRow)
        {
            // 1열1행 : A1, 2열1행 : B1 과 같이 해당 Cell 이름으로 바꾸는 함수
            // Excel Column 이름 규칙 : A, B, C, ..., Z, AA, AB, ...
            int i, j;
            string Temp;
            try
            {
                string str = "";
 
                Temp = "";
                if (StartColumn > 0 & StartRow > 0)
                {
                    if (StartColumn < 27)
                        Temp = ((char)(64 + StartColumn)).ToString();
                    else
                    {
                        i = StartColumn / 26;
                        j = StartColumn % 26;
                        if (i < 27)
                        {
                            if (j > 0)
                                Temp = ((char)(64 + i)).ToString() + ((char)(64 + j)).ToString();
                            else if (j == 0)
                                Temp = ((char)(64 + i - 1)).ToString() + ((char)(64 + 26)).ToString();
                        }
                    }
                    str = Temp + StartRow;
                }
 
                return str;
            }
            catch
            {
                return "";
            }
        }
 
        private static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}
 
cs

 

4. 메인 클래스에서 사용하기

 

 

 

(참고) NumberFormat 지정방법

2024.04.08 - [IT/C#] - [C#] Excel NumberFormat 표시 형식 지정해서 저장하기

 

[C#] Excel NumberFormat 표시 형식 지정해서 저장하기

2024.03.14 - [IT/C#] - [C#] Excel 사용하기. Create Excel File + Update Excel File [C#] Excel 사용하기. Create Excel File + Update Excel File [ C# Excel 사용하기 ] 1. 참조 추가하기 * 해당 PC에 Excel이 설치되어 있어야 하며, 엑

ella-devblog.tistory.com

 

728x90
반응형