using System; using System.Data; using System.Drawing; using System.IO; using System.Windows.Forms; using ExcelDataReader; namespace ReadExcel { /// <summary> /// C#读取Excel文件(.xls .xlsx) /// LDH @ 2021-7-28 /// Nuget: ExcelDataReader ExcelDataReader.DataSet /// </summary> public partial class FrmMain : Form { private DataTableCollection _tableCollection; public FrmMain() { InitializeComponent(); } /// <summary> /// 打开Excel表格,支持 .xlsx .xls 两种格式 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnBrowse_Click(object sender, EventArgs e) { using (var openFileDialog = new OpenFileDialog {Filter = @"Excel表格|*.xlsx|Excel|*.xls"}) { if (openFileDialog.ShowDialog() == DialogResult.OK) { txtFileName.Text = openFileDialog.FileName; using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read)) { using (var reader = ExcelReaderFactory.CreateReader(stream)) { var result = reader.AsDataSet(new ExcelDataSetConfiguration { ConfigureDataTable = _ => new ExcelDataTableConfiguration {UseHeaderRow = true} }); _tableCollection = result.Tables; cboSheet.Items.Clear(); foreach (DataTable item in _tableCollection) cboSheet.Items.Add(item.TableName); } } } } } private void cboSheet_SelectedIndexChanged(object sender, EventArgs e) { BindDataForDataGridView(); } /// <summary> /// 给DataGridView绑定数据源 /// </summary> private void BindDataForDataGridView() { var dt = _tableCollection[cboSheet.SelectedItem.ToString()]; DataGridViewHelper.BindDataGridViewFillShow(dt, dataGridView1, Color.BlueViolet); dataGridView1.DataSource = dt; // DataGridView取消选中第一行第一列方法(绑定数据源后) dataGridView1.Rows[0].Cells[0].Selected = false; dataGridView1.Rows[0].Selected = false; } } }
/// <summary> /// 铺满显示,绑定DataGridView数据源后 /// LDH @ 2021-7-28 /// </summary> /// <param name="dt">DataTable</param> /// <param name="dgv">DataGridView</param> /// <param name="headerFontColor">表头字体颜色设置</param> public static void BindDataGridViewFillShow(DataTable dt, DataGridView dgv, Color headerFontColor) { dgv.ClearSelection(); dgv.AllowUserToAddRows = false; dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; // 平均分平铺显示 dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 设置为整行被选中 // 给表头内容换颜色 dgv.EnableHeadersVisualStyles = false; // 这样就可以使用当前的主题的样式了,这句话十分关键! dgv.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 12, FontStyle.Bold); dgv.ColumnHeadersDefaultCellStyle.ForeColor = headerFontColor; dgv.DataSource = null; dgv.DataSource = dt; }