본문 바로가기
Windows/WPF

WPF, C# 엑셀(excel) 파일을 DataGrid에 가져오기

by Planetis 2015. 11. 16.

Header

using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data;


C# Code

private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog oFileDialog = new OpenFileDialog();
    oFileDialog.Filter = "Excel (*.xlsx)|*.xlsx|Excel 97-2003 (*.xls)|*.xls";

    if (oFileDialog.ShowDialog() == false) {
        return;
    }

    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    Excel.Range range;

    string str;
    int rCnt = 0;
    int cCnt = 0;
    string sCellData = "";
    double dCellData;

    xlApp = new Excel.Application();

    try {
        xlWorkBook = xlApp.Workbooks.Open(oFileDialog.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        range = xlWorkSheet.UsedRange;

        DataTable dt = new DataTable();

        // 첫 행을 제목으로
        for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++) {
            str = (string)(range.Cells[1, cCnt] as Excel.Range).Value2;
            dt.Columns.Add(str, typeof(string));
        }

        for (rCnt = 2; rCnt <= range.Rows.Count; rCnt++) {
            string sData = "";
            for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++) {
                try {
                    sCellData = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
                    sData += sCellData + "|";
                } catch (Exception ex) {
                    dCellData = (range.Cells[rCnt, cCnt] as Excel.Range).Value2;
                    sData += dCellData.ToString() + "|";
                }
            }
            sData = sData.Remove(strData.Length - 1, 1);
            dt.Rows.Add(sData.Split('|'));
        }

        dataExcel.ItemsSource = dt.DefaultView;

        xlWorkBook.Close(true, null, null);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);
    } catch (Exception ex) {
        MessageBox.Show("파일 열기 실패! : " + ex.Message);
        return;
    }
}

private void releaseObject(object obj)
{
    try {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    } catch (Exception ex) {
        obj = null;
        MessageBox.Show("Unable to release the Object " + ex.ToString());
    } finally {
        GC.Collect();
    }
}


Xaml

<Window x:Class="ExceltoJson.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Excel to DataGrid" Height="350" Width="425">
    <Grid>
        <Button x:Name="btnOpenFile" Content="Open Excel File" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="110" Click="btnOpenFile_Click"/>
        <DataGrid x:Name="dataExcel" HorizontalAlignment="Left" Margin="10,35,10,10" VerticalAlignment="Center" Height="264" Width="389"/>
    </Grid>
</Window>



320x100

댓글