首页 > 代码库 > winform下读取excel文件并绑定datagridview例子

winform下读取excel文件并绑定datagridview例子

首先我要读取这个excel文件然后生成Datable 

用winform编程的方式

前台界面:

 后台的代码

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.OleDb;namespace 读Excel文件{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        /// <summary>        /// 选择文件按钮        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void button1_Click(object sender, EventArgs e)        {            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)            {                this.textBox1.Text = this.openFileDialog1.FileName;            }        }        /// <summary>        /// 点击导出excel按钮        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void button2_Click(object sender, EventArgs e)        {            string File = this.openFileDialog1.FileName;            DataTable dt = ExcelUp(File);            dataGridView1.AutoGenerateColumns = false;            dataGridView1.DataSource = dt;        }        /// <summary>        /// 读取指定excel表中的内容返回datatable        /// </summary>        /// <param name="fileName">文件地址</param>        /// <returns>表中内容</returns>        public DataTable ExcelUp(string fileName)        {            string filePath = fileName;//读取excel文件路径;            DataTable dt = GetDataTable("Sheet1", filePath);            return dt;        }        /// <summary>        /// 读取excel指定页中的内容        /// </summary>        /// <param name="strSheetName">页名</param>        /// <param name="strExcelFileName">excel路径</param>        /// <returns></returns>        protected DataTable GetDataTable(string strSheetName, string strExcelFileName)        {            //源的定义            string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1‘;", strExcelFileName);            //Sql语句            string strExcel = string.Format("select * from [{0}$]", strSheetName);            //定义存放的数据表            DataSet ds = new DataSet();            //连接数据源            OleDbConnection conn = new OleDbConnection(strConn);            try            {                conn.Open();                //适配到数据源                OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);                adapter.Fill(ds, strSheetName);            }            catch (Exception e)            {                throw e;            }            finally            {                conn.Close();            }            return ds.Tables[strSheetName];        }    }}

 

实现的效果:(说明:在excel中读取的datable中列头都是F几,如F1,F2等,要自己转换)

winform下读取excel文件并绑定datagridview例子