Application/C# (WinForm)

[C# WinForm] 엑셀 파일 사용 하기 (Excel)

devsalix 2023. 1. 19. 15:43
728x90

C#에서 OleDb와  DataTable을 사용해 Excel 파일을 접근하여 사용할 수 있습니다

 

우선 Excel 클래스로는 

 

using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

public class CExcel
{
    private OleDbConnection m_Conn = null;
    private OleDbCommand m_Comm = null;

    public bool Open(string sFileName)
    {
        try
        {
            string sConn = string.Empty;

            if (sFileName.Substring(sFileName.Length - 4, 4).ToLower().Equals("xlsx"))
            {
                sConn = "Provider=Microsoft.ACE.OLEDB.12.0;"
                      + "Extended Properties=Excel 12.0;"
                      + "Data Source=" + sFileName;
            }
            else
            {
                sConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
                      + "Extended Properties=Excel 8.0;"
                      + "Data Source=" + sFileName;
            }

            m_Conn = new OleDbConnection(sConn);

            m_Comm = new OleDbCommand();
            m_Comm.Connection = m_Conn;

            m_Conn.Open();

            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "EXCEL 열기 실패");
        }

        return false;
    }

    public void Close()
    {
        try
        {
            if(m_Comm != null)
            {
                m_Comm.Dispose();
            }
            
            if(m_Conn != null)
            {
                m_Conn.Close();
                m_Conn.Dispose();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("EXCEL 닫기 실패\n" + ex.Message);
        }
    }

    public bool DB_COMMAND(string sQuery)
    {
        try
        {
            m_Comm.CommandText = sQuery;
            m_Comm.ExecuteNonQuery();

            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show("EXCEL Command 실패\n" + ex.Message);
        }

        return false;
    }

    public bool DB_SELECT(string sQuery, ref DataTable dt)
    {
        try
        {
            m_Comm.CommandText = sQuery;
            OleDbDataAdapter Adapter = new OleDbDataAdapter(m_Comm);
            Adapter.Fill(dt);

            if (dt.Rows.Count <= 0) dt = null;

            Adapter.Dispose();

            return true;
        }
        catch (Exception ex)
        {
            dt = null;
            MessageBox.Show("EXCEL Select 실패\n" + ex.Message);
        }

        return false;
    }
}

 

위와 같이 코드를 짜면 기본적인 SELECT, UPDATE, DELETE 구문으로 이용 가능합니다

 

간단히 SELECT를 예를 들어서

 

private bool GetFileData(string strPath)
{
	CExcel Excel = new CExcel();
	DataTable dt = new DataTable();
	string strQuery;

	if (Excel.Open(strPath) == false)
	{
		return false;
	}

	m_arNumber.Clear();
	m_arLuckNumber.Clear();

	strQuery = "SELECT * FROM [Sheet1$]";
	if (Excel.DB_SELECT(strQuery, ref dt))
	{
		///처리 코드
		Excel.Close();
		return true;
	}
    
	Excel.Close();
	return false;
}

 

이와 같이 작성하면 Excel의 데이터를 모두 가져와

 

처리 코드 부분에서 특정값을 가져와 처리가 가능합니다

 


제 글이 도움이 되셨다면 댓글 & 공감 부탁드려요 😀

 

 
728x90
반응형
댓글수0