Programming/C#

How to create Excel file in C#(Source)

blueasa 2014. 3. 26. 17:58

xls와 xlsx 둘 다 되도록 예제를 약간 수정해서 테스트 완료.


P.s. 무슨 이유인지 모르지만 VS2013에서는 Microsoft.Office.Interop.Excel 이 없어서, 부득이하게 VS2010으로 작업함.

       (VS2012는 있는지 확인은 안해봤지만.. 얼핏 인터넷에서 보기로는 VS2012도 없는 듯..)

        
        private void CreateExcelFile()
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.Application();
            // 생성할 때, 기본 Sheet 1개.
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            // Sheet 추가.(필요한 Sheet 개수에 따라 루프 돌아야 될 듯)
            xlWorkBook.Worksheets.Add(misValue, misValue, misValue, misValue);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            // Sheet Name 지정.
            xlWorkSheet.Name = "SheetName1";
            xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
            xlWorkSheet.Name = "SheetName2";
            xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

            // 테스트용으로 파일명 직접 입력.
            string createFilePath = Directory.GetCurrentDirectory() + @"\" + "csharp-Excel.xlsx";

            // 파일 있으면 삭제.
            if (true == File.Exists(createFilePath))
            {
                File.Delete(createFilePath);
            }

            // 확장자만 검사하기 위해..
            string strExtension = Path.GetExtension(createFilePath);

            if (0 == strExtension.CompareTo(".xlsx"))
            {
                xlWorkBook.SaveAs(createFilePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, false, false, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlUserResolution, true, misValue, misValue, misValue);
            }
            else if (0 == strExtension.CompareTo(".xls"))
            {
                xlWorkBook.SaveAs(createFilePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            }

            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            MessageBox.Show("Excel file created , you can find the file " + createFilePath);
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }



엑셀 생성 참조 : http://csharp.net-informations.com/excel/csharp-create-excel.htm

xlsx 참조 : http://stackoverflow.com/questions/9769703/exporting-to-xlsx-using-microsoft-office-interop-excel-saveas-error


반응형