C#에서 Excel 제어를 위한 클래스 구현

Software/C#|2022. 12. 29. 09:56
반응형

계측장비에서 측정된 데이타를 Excel 파일로 저장하기 위한 Class 구현 

using Microsoft.Office.Interop.Excel ;    
namespace ExcelControl
{
    public class CExcelControl : IDisposable
    {
        private Microsoft.Office.Interop.Excel.Application? application = null;
        private Workbook? workBook = null;
        private Worksheet? workSheet = null;
        public bool Visible { get; set; } = false ;

        public CExcelControl(bool visible)
        {
            this.Visible = visible ;
        }

        public bool Create()
        {
            bool result = true;

            try
            {
                application = new Microsoft.Office.Interop.Excel.Application();  //Excel 프로그램 실행
                application.Visible = this.Visible ;                             //Excel 화면 띄우기 옵션
                workBook = application.Workbooks.Add();
            }
            catch (Exception)
            {
                result = false;
            }

            return result;
        }

        public void addSheet(string sheetName)
        {
            if (workBook != null)
            {
                workSheet = workBook.Worksheets.Add(After: workBook.Worksheets.Item[workBook.Worksheets.Count]);
                workSheet.Name = sheetName;
            }
        }

        public bool saveExcelSheep(string fileName)
        {
            bool result = true;

            if (workBook != null)
            {
                try
                {
                    workBook.SaveAs(fileName, XlFileFormat.xlWorkbookDefault);
                }
                catch (Exception)
                {
                    result = false;
                }
            }

            return result;
        }

        public void writeSheet(Action<Worksheet> Information, string sheetName)
        {
            if (workBook != null)
            {
                workSheet = workBook.Worksheets.Item[sheetName];
                if (workSheet != null)
                {
                    Information(workSheet);
                }
            }
        }

        public void Dispose()
        {
            workBook!.Close(true);   
            application!.Quit();

            if(workBook != null) Marshal.ReleaseComObject(workBook) ;
            if(application != null) Marshal.ReleaseComObject(application) ;
        }  
    }
}

사용방법

   

private void btnOpen_Click(object sender, EventArgs e)
{
    using(CExcelControl excel = new CExcelControl(true))  // 엑셀 객체 생성
    {
        excel.Create() ;                                  //  Excel 프로그램 실행 
        excel.writeSheet(writeSheetHeader, "Sheet1") ;    // Sheet1 에 데이타 저장 
        excel.saveExcelSheep("d:\test.xlsx") ;            // Excel 파일 저장 
    }
}

private void writeSheetHeader(Worksheet workSheet)
{
    workSheet.Cells[1, 1] = "Data1";
    workSheet.Cells[1, 2] = "Data2";
    workSheet.Cells[1, 3] = "Data3"; 
}
반응형

댓글()