첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170
using System.Data;
using System.Data.OleDb;

#region 엑셀 XLS 파일 데이터 구하기 - GetXLSFileData(filePath, isFirstRowAsColumnName, sheet)

/// <summary>
/// 엑셀 XLS 파일 데이터 구하기
/// </summary>
/// <param name="filePath">파일 경로</param>
/// <param name="isFirstRowAsColumnName">첫번째 행 컬럼명 여부</param>
/// <param name="sheet">시트명</param>
/// <returns>엑셀 XLS 파일 데이터</returns>
public DataTable GetXLSFileData(string filePath, bool isFirstRowAsColumnName, string sheet)
{
    string strConnection = string.Format
    (
        "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;Imex=1;HDR={1};\"",
        filePath,
        isFirstRowAsColumnName ? "Yes" : "No"
    );

    OleDbConnection oleDbConnection = null;

    try
    {
        oleDbConnection = new OleDbConnection(strConnection);

        oleDbConnection.Open();

        OleDbCommand oleDbCommand = new OleDbCommand();

        oleDbCommand.Connection  = oleDbConnection;
        oleDbCommand.CommandType = CommandType.Text;
        oleDbCommand.CommandText = string.Format("SELECT * FROM [{0}$]", sheet);

        OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(oleDbCommand);

        DataTable table = new DataTable(sheet);

        oleDbDataAdapter.Fill(table);

        return table;
    }
    finally
    {
        if(oleDbConnection != null)
        {
            if(oleDbConnection.State != ConnectionState.Closed)
            {
                oleDbConnection.Close();
            }
        }
    }
}

#endregion
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요