DBILITY

C# Excel Data To DataGridView Using ExcelDataReader 본문

카테고리 없음

C# Excel Data To DataGridView Using ExcelDataReader

DBILITY 2025. 10. 9. 09:09
반응형

VS2017. Nuget Manager에서 ExcelDataReader,  ExcelDataReader.DataSet  버전 3.8.0 을 설치한다.

UI는 코드보고 그냥 그리고, 코딩하고 실행해 보면 그리드에 잘 표시된다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExcelDataReader;

namespace CSharpTest
{
    public partial class FrmExcelOpen : Form
    {
        private OpenFileDialog fileDialog;
        private DataTable dt;

        public FrmExcelOpen()
        {
            InitializeComponent();

            fileDialog = new OpenFileDialog
            {
                Multiselect = false,
                AddExtension = true,
                CheckFileExists = true,
                Filter = "All Excel File(*.xls;*.xlsx)|*.xls;*.xlsx|Microsoft Excel 97-2003 Workbook (*.xls)|*.xls|Microsoft Excel Workbook (*.xlsx)|*.xlsx",
                FilterIndex = 3
            };

            dgv1.MultiSelect = false;
            dgv1.ReadOnly = true;
            dgv1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

        }

        private void btnOpenExcelFile_Click(object sender, EventArgs e)
        {
            
            if (fileDialog.ShowDialog() == DialogResult.OK) {
                using(var stream = File.Open(fileDialog.FileName,FileMode.Open, FileAccess.Read))
                {
                    if(Path.GetExtension(fileDialog.FileName).ToUpper() == ".XLSX" 
                        || Path.GetExtension(fileDialog.FileName).ToUpper() == ".XLS")
                    {
                        using (var reader = ExcelReaderFactory.CreateReader(stream))
                        {
                            var result = reader.AsDataSet(new ExcelDataSetConfiguration() {
                                ConfigureDataTable = (_) => new ExcelDataTableConfiguration
                                {
                                    EmptyColumnNamePrefix = "Column",
                                    UseHeaderRow = false
                                }
                            });
                            dt = result.Tables[0];
                            dgv1.DataSource = dt;

                        }
                    }
                }
            }

        }
    }
}
반응형
Comments