• C#에서 Excel 읽고 쓰기
    프로그래밍/C# + Unity 2019. 2. 21. 22:58
    728x90

    Nuget 패키지 추가

    C#에서는 'Microsoft.Office.Interop.Excel'를 참조하면 엑셀 파일을 불러들여서 읽고 쓰기를 수행할 수 있다.

    사용 방법은 프로젝트 생성 → Nuget 패키지 관리 → Microsoft.Office.Interop.Excel 선택

     

     

    소스 코드

    using System.IO;
    using System.Windows.Forms;
    using Excel = Microsoft.Office.Interop.Excel;
    namespace CsharpUseExcel {
        public partial class Form1 : Form {
            public Form1() {
                InitializeComponent();
            }
    
            Excel.Workbook wb = null;
            Excel.Worksheet ws = null;
            Excel.Application ap = null;
    
            private void button1_Click(object sender, EventArgs e) {
                try {
                    String filepath = ShowFileOpenDialog();
                    if (filepath != null) {
                        ap = new Excel.Application();
                        wb = ap.Workbooks.Open(filepath, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                        ws = wb.Worksheets.get_Item("과일");
                        ap.Visible = false;
    
                        String[] 과일이름 = "" + ws.get_Range("B2:B3").Value;
                        Console.WriteLine(과일이름[0] + " " + 과일이름[1]);
    
                        /*메모리 할당 해제*/
                        DeleteObject(ws);
                        DeleteObject(wb);
                        ap.Quit();
                        DeleteObject(ap);
                        /*메모리 할당 해제*/
                    }
                } catch (Exception ex) {
                    MessageBox.Show("에러" + ex.Message, "에러!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
    
            private void DeleteObject(object obj) {   // 메모리 해제를 위한 사용자 정의 함수
                try {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                    obj = null;
                } catch (Exception ex) {
                    obj = null;
                    MessageBox.Show("메모리 할당을 해제하는 중 문제가 발생하였습니다." + ex.ToString(), "경고!");
                } finally {
                    GC.Collect();
                }
            }
    
        }
    }

     

    위 소스를 보면 FileDialog로 파일의 경로를 가져오고 '과일'이라는 워크시트를 열어 'B2:B3'구역의 값을 String[]인 과일 이름에 담에 출력하는 로직이다.

     

    워크시트 명은 엑셀 파일의 이름이 아닌 엑셀 파일 내의 구역 이름을 뜻한다.

    값을 불러올 때 쓸 때 둘 다 'get_Range().Value'를 사용한다.

    불러올 땐 String tmp = get_Range("A1").Value;

    쓸 땐 get_Range("A1").Value = "사과";


    728x90

    댓글

Copyright ⓒ syudal.tistory.com