본문 바로가기
백엔드/C#

엑셀파일 읽기

by 1005ptr 2018. 5. 13.
반응형

엑셀파일 읽어오기

출처 : http://gigong.cf/4


0-1. 참조 파일 추가



0-2. Microsoft Excel 16.0 Object Library 선택




0-3. using 구문 추가

using System.Runtime.InteropServices;

using Excel = Microsoft.Office.Interop.Excel;


1. ReadExcelData - 엑셀 데이터를 읽어 List<List<String>>으로 변환

        private List<List<String>> ReadExcelData(string excelFilePath)

        {

            List<List<String>> excelData = null;

            List<String> rowData = null;

            Excel.Application excelApp = null;

            Excel.Workbook wb = null;

            Excel.Worksheet ws = null;

            try

            {

                excelApp = new Excel.Application();

                wb = excelApp.Workbooks.Open(excelFilePath);

                ws = wb.Worksheets.get_Item(1) as Excel.Worksheet;

                Excel.Range rng = ws.UsedRange;


                object[,] data = rng.Value;

                excelData = new List<List<string>>(data.GetLength(0));

                for (int r = 1, i = 0; r <= data.GetLength(0); r++)

                {

                    rowData = new List<string>(data.GetLength(1));

                    for (int c = 1; c <= data.GetLength(1); c++)

                    {

                        if (data[r, c] == null)

                        {

                            continue;

                        }

                        rowData.Add(data[r, c].ToString());

                    }

                    excelData.Add(rowData);

                }

                wb.Close(true);

                excelApp.Quit();

                return excelData;

            }

            catch (Exception ex)

            {

                throw ex;

            }

            finally

            {

                ReleaseExcelObject(ws);

                ReleaseExcelObject(wb);

                ReleaseExcelObject(excelApp);

            }

        }


2. ReleaseExcelObject - 메모리 정리

        static void ReleaseExcelObject(object obj)

        {

            try

            {

                if (obj != null)

                {

                    Marshal.ReleaseComObject(obj);

                    obj = null;

                }

            }

            catch (Exception ex)

            {

                obj = null;

                throw ex;

            }

            finally

            {

                GC.Collect();

            }

        }


반응형

'백엔드 > C#' 카테고리의 다른 글

배열의 처음과 끝을 연결하기  (0) 2018.06.06
자주 쓰는 단축키  (0) 2018.06.04
파일 경로 찾기 - OpenFileDialog  (0) 2018.05.13
DataTable을 DataGridView에 DataBinding  (0) 2018.05.11
Form을 하나만 열고 싶을 때  (0) 2018.05.11

댓글