티스토리 뷰

C# / .NET 에서 엑셀2010 파일 읽기. (엑셀파일 읽기)

나중에 DataTable 이나 DataSet 형태로 가공해서 사용하면되는거고.

지금은 그냥 엑셀파일에 접근해서 해당 시트에 있는 데이터를 가져오는것에 대해 의의를 둔다.

OLEDB를 이용해서 쿼리날리듯이도 가져올 수 있는데 버전맞추기 귀찮아서 그냥 Workbook 클래스를 사용한다.


값을 읽어들이는 것보다

중요한건 엑셀 COM 객체를 사용하면 해당 class 를 Quit(); 해주거나 close 해주어도

EXCEL.EXE 가프로세스에서 사라지지 않는다. 환장할 노릇이지 아주..


원인:

COM 객체와 닷넷의 가비지 컬렉션이 서로 궁합이 잘 맞지 않는다는 것이며 Excel 프로세스가 종료하기 위해서는 생성된 모든 엑셀 COM 객체들(Application, Workbook Sheet 등등)이 해제(release)되어야 하기 때문

해결방안:

COM 객체를 닷넷에서 다루고자 한다면 참조한 모든 COM 객체는 죄다 명시적으로 해제를 하면 된다. COM 객체를 해제하는 구체적인 방법은 System.Runtime.InteropServices 네임스페이스의 Marshal 클래스가 제공하는 ReleaseComObject 메쏘드를 호출

내용 출처 : http://www.simpleisbest.net/archive/2005/05/31/156.aspx



코드 : 

   Excel.Application objExcelApp;

                Excel._Workbook objBook;


                Excel.Workbooks objBooks;

                Excel.Sheets objSheets;

                Excel._Worksheet objSheet;

                Excel.Range rngLast;


                string valueString = string.Empty;


                objExcelApp = new Microsoft.Office.Interop.Excel.Application();

                objBooks = (Excel.Workbooks)objExcelApp.Workbooks;

                //Open the workbook containing the address data.

                objBook = objBooks.Open(@"C:\1.xlsx", Missing.Value, Missing.Value,

                Missing.Value, Missing.Value,

                Missing.Value, Missing.Value,

                Missing.Value, Missing.Value,

                Missing.Value, Missing.Value,

                Missing.Value, Missing.Value,

                Missing.Value, Missing.Value);

                //Get a reference to the first sheet of the workbook.

                objSheets = objBook.Worksheets;

                objSheet = (Excel._Worksheet)objSheets.get_Item(1);


                //Select the range of data containing the addresses and get the outer boundaries.

                rngLast = objSheet.get_Range("A1").SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell);

                long lLastRow = rngLast.Row;

                long lLastCol = rngLast.Column;


                // Iterate through the data and concatenate the values into a comma-delimited string.

                for (long rowCounter = 1; rowCounter <= lLastRow; rowCounter++)

                {

                    for (long colCounter = 1; colCounter <= lLastCol; colCounter++)

                    {

                        //Write the next value into the string.

                        Excel.Range cell = (Excel.Range)objSheet.Cells[rowCounter, colCounter];

                        string cellvalue = cell.Value.ToString();

                        //TODO: add your business logic for retrieve cell value

                        Marshal.ReleaseComObject(cell);

                    }

                }

                objBook.Close();

                objBooks.Close();  

                objExcelApp.Quit();


                // 명시적으로 COM 객체를 해제해 주려면 엑셀에 접근하는 모든 코드자체를 아래와같이 ReleseComObject 시켜주어야 한다. 하지않으면 프로세스에 EXCEL.EXE가 계속 남아있는다.

                Marshal.ReleaseComObject(objExcelApp);

                Marshal.ReleaseComObject(objBook);

                Marshal.ReleaseComObject(objBooks);

                Marshal.ReleaseComObject(objSheet); 

                Marshal.ReleaseComObject(objSheets);

                Marshal.ReleaseComObject(rngLast);

            } 


소스출처 : http://yanziyang.wordpress.com/2010/11/12/using-c-to-read-data-from-excel-2010-cells/


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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
글 보관함