C#

[C#]Excel 파일의 Sheet 이름 얻어오기 예제

선영아 사랑해 2016. 2. 19. 13:38

엑셀 파일에서 Sheet 이름 얻어오기 위한 함수입니다.

검색을 하다보면 다른 방법도 존재하오니 참고용으로 확인해보세요.


 using System.IO;
using System.Data.OleDb;


public string[] GetExcelSheetNames(string excelFileName)
        {
            OleDbConnection con = null;

            DataTable dt = null;
           
            String conStr = "";

            if (Path.GetExtension(excelFileName).Equals(".xls"))
            {
                conStr = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + excelFileName + ";Extended Properties=Excel 8.0;";
            }
            else if (Path.GetExtension(excelFileName).Equals(".xlsx"))
            {
                conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFileName + ";Extended Properties=Excel 12.0;";
            }

            con = new OleDbConnection(conStr);
           
            con.Open();
           
            dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            if (dt == null)
            {
                return null;
            }

            String[] excelSheetNames = new String[dt.Rows.Count];

            int i = 0;

            foreach (DataRow row in dt.Rows)
            {
                excelSheetNames[i] = row["TABLE_NAME"].ToString();

                i++;
            }

            return excelSheetNames;
        }