IT/C#

[C#] Excel Data to DataGridView with OleDB

Ella.J 2023. 1. 13. 13:45
728x90
반응형

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
private string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
 
public void ReadExcel(string filePath, string fileExtension)
{
    string connectionString = string.Empty;
    string sheetName = string.Empty;
 
    // 확장자로 구분하여 커넥션 스트링을 가져옮
    switch (fileExtension)
    {
        case ".xls":    //Excel 97-03
            connectionString = string.Format(Excel03ConString, filePath, "YES");
            break;
        case ".xlsx":  //Excel 07
            connectionString = string.Format(Excel07ConString, filePath, "YES");
            break;
    }
 
    // 첫 번째 시트의 이름을 가져옮
    using (OleDbConnection con = new OleDbConnection(connectionString))
    {
        using (OleDbCommand cmd = new OleDbCommand())
        {
            cmd.Connection = con;
            con.Open();
            System.Data.DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
            con.Close();
        }
    }
 
    // 첫 번째 시트의 데이타를 읽어서 datagridview 에 보이게 함.
    using (OleDbConnection con = new OleDbConnection(connectionString))
    {
        using (OleDbCommand cmd = new OleDbCommand())
        {
            using (OleDbDataAdapter oda = new OleDbDataAdapter())
            {
                DataTable dt = new DataTable();
                cmd.CommandText = $"SELECT * FROM [{sheetName}]";
                cmd.Connection = con;
                con.Open();
                oda.SelectCommand = cmd;
                oda.Fill(dt);
                con.Close();
 
                //Populate DataGridView.
                dataGridView1.DataSource = dt;
                dataGridView1.Columns[0].Width = 150;
            }
        }
    }
}
cs

 

 

728x90
반응형