코딩-C#

c# 엑셀 interop 대신 쓸수 있는 EP plus 엑셀 export 샘플

JL(제이엘) 2021. 9. 7. 15:26
728x90
반응형

망할 Interop 정말 불편하다

여러모로 버전 맞춰줘야하는것도 있고

레지스트리를 건드려서 오류도 개별적으로 잡아줘야하고

 

 

그럴때 다른 플러그인이 없을까 알아보다가

EP Plus 란 .NET nuget 패키지를 발견했다.

https://epplussoftware.com/

 

Excel spreadsheet library for .NET Framework/Core - EPPlus Software

EPPlus 5 is available on Nuget! EPPlus 5.7.4 was published on the EPPlus Nuget feed on August 26, 2021. Changelog New features in EPPlus 5 Features and improvements in the new version. Support all Excel 2019 chart types with the new, modern styling - Check

epplussoftware.com

 

Nuget 패키지 관리자 > Nu Get 패키지 관리 > EP PLUS > 4.5.3.3 으로 설치!

 

아래는 EP PLUS를 이용해서 dataTable을 읽어 파일을 내려주는 코드이다.

 

        public void setExportEpPlus(DataTable ds , string current_time)
        {
        	//파일이름 지정
            string fileName = "invoice_" + current_time + ".xlsx";

            //-------------엑셀 Export 시작 --------------

            ExcelPackage pck = new ExcelPackage();
            
				//엑셀 시트 이름을 Var에 저장
                var wsheet = pck.Workbook.Worksheets.Add("Sheet1");

                for (var i = 0; i < ds.Columns.Count; i++)
                {
                    wsheet.Cells[1, i + 1].Value = ds.Columns[i].ColumnName;
                }

                for (var i = 0; i < ds.Rows.Count; i++)
                {
                    for (var j = 0; j < ds.Columns.Count; j++)
                    {
                        wsheet.Cells[i + 2, j + 1].Value = ds.Rows[i][j];
                    }
                }

			//파일 저장경로 + 파일이름
            if (File.Exists(paths + fileName))
            {
                File.Delete(paths);
            }

            // 엑셀파일을 물리디스크에 저장
            FileStream objFileStrm = File.Create(paths + fileName);
            objFileStrm.Close();

            // 엑셀파일로 쓰기
            File.WriteAllBytes(paths + fileName, pck.GetAsByteArray());

            //------------ 엑셀파일 생성 완료 ------------
            //Close Excel package
            pck.Dispose();


        }

 

너무 편하다.

오류도 없이 깔끔하게 Export 됨.

 

728x90
반응형