在winForm中如何把Excel文件导入到DataGridView中,用C#语言

解决方案 »

  1.   

    可以读出到DataTable中然后在绑定
    Excel 可以想操作数据库中的表那样被查询
    当然也可以一行一行的读取
      

  2.   

    我最近刚做的一个,不过是在web程序里Excel文件导入到GridView中,希望对你有帮助#region 002----从Excel文件填充DataSet
        /// <summary>
        /// 将Excel文件转换成DataSet
        /// </summary>
        /// <param name="filepath">Excel文件全路径</param>
        /// <param name="sheetname">Excel文件Sheet表名</param>
        /// <returns></returns>
        public DataSet ExcelDataSource( string filepath , string sheetname )
        {
            string strConn;
            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(strConn);
            OleDbDataAdapter oada = new OleDbDataAdapter ( "select * from [" + sheetname + "$]", strConn );
            DataSet ds = new DataSet ();
            oada.Fill ( ds );
            return ds ;
        }
    #endregion
    调用部分protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridView2.DataSource = ExcelDataSource(Server.MapPath("~/TOP_exceltest.xls"),"Sheet1");
                GridView2.DataBind();
            }    }
      

  3.   


    string filename = @"C:\Test Excel\a.xls";//Excel文件地址。
                string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filename + ";Extended Properties='Excel 8.0;'";
                string strSQL = "Select * From [Sheet1$]";
                DataSet ds = new DataSet();
                OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, strConn);
                adapter.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
      

  4.   

    楼上的兄弟能提供winForm版的吗
    我到网上搜了一下
    好多代码全都不管用
      

  5.   

    嵌入GridView的话,最后不要一行一行的读取,那样会走很多弯路比如Excel里面有单引号等违法字符串的时候经常出错误,所以直接映射到dataset里面就好了,最后数据插入数据库的时候如果文件里面有非法字符的话再统一做异常处理或者正则表达式然后事务处理就行了
      

  6.   

    楼主找到winForm版解决以后也发出来给我看看好吗?最近在弄winForm的程序,想学习
      

  7.   

    你直接把代码放到一个类里面,然后在winform中调用这个类不就可以了嘛
      

  8.   

    我的意思是点击导入按钮的时候
    弹出系统对话框
    让你选择方件
    点击保存的时候
    DataGridView就显示Excel中的信息
    拜托各位谁能提完整的代码?
      

  9.   

    using System.Data.OleDb;  if (MessageBox.Show("导入采集未成功的高校url,请首先导出已经采集完的高校信息!并确保当前省份与您要导入excel中省份相同.", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    //去处
                    this.dataGridView1.Rows.Clear();
                    OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    openFileDialog1.ShowDialog();
                    string Path = openFileDialog1.FileName;
                    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";                OleDbConnection conn = new OleDbConnection(strConn);
                    string strExcel = "";
                    strExcel = "select * from [sheet1$]";
                    OleDbCommand cmd = new OleDbCommand(strExcel, conn);
                    try
                    {
                        conn.Open();
                        OleDbDataReader reader = cmd.ExecuteReader();
                        
                        while (reader.Read())
                        {
                            string schoolName = reader[0].ToString().Trim();
                            string schoolUrl = reader[1].ToString().Trim();
                            if (!string.IsNullOrEmpty(schoolName) && !string.IsNullOrEmpty(schoolUrl))
                            {
                                int index2 = dataGridView1.Rows.Add();
                                DataGridViewRow newrow1 = dataGridView1.Rows[index2];
                                newrow1.Cells[0].Value = schoolName;//院校名称
                                newrow1.Cells[1].Value = schoolUrl;
                                newrow1.Cells[2].Value = "就绪";//采集状
                            }
                        }
                        MessageBox.Show("excel 导入成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {                    MessageBox.Show("导入excel出错."+"\n"+ex.Message);                }
                    finally
                    {
                        conn.Close();
                    }
                    conn.Close();                
                }
            }
            #endregion
      

  10.   

    我刚才给你的就是那样的代码,虽然不是winForm的,你可以做修改阿(如果winForm有基础的话)。
    我写成两个方法了,所以第2个方法你直接放到你的按钮事件里面就可以了,文件要放在你项目的文件夹里面,如果想自己找的话就用开发环境自带的上传文件控件就可以了。
    说一下思路:
    你把你的窗体里面放一个长传文件的空间然后把我给你的第一个方法放到上传文件控件的按钮里面,显示信息的时候,显示按钮里面放我的第二个方法到你的DataGridView里面。
    前提,你改一下程序。
    顺便说一下,我觉得你找十全十美的代码直接调用还不如自己动手,这样记得快,最后别人的代码就成为自己的了,一举两得么不是,呵呵。加油
      

  11.   

    最近也在研究这个问题,感觉Excel导入数据很麻烦,一旦Excel表中的格式变了,就会导不进来
      

  12.   

    是呀,而且我发现一个问题,如果sheet有很多,或者是表格做的很漂亮那种就不知道怎么导好了~~当初不介意一行一行的导就是因为Excel的行为很诡异,很难控制它。所以我们开发的时候都避开.xsl用它的.csv文件导入。
      

  13.   

    避开.xsl用它的.csv文件导入这两者区别,很大么?新手求教 ?
      

  14.   


            private void btnImport_Click(object sender, EventArgs e)
            {
                string fileName = GetExcelPath();
                DataTable dt = DoImport(fileName);            this.dataGridView1.DataSource = dt;
            }
            private string GetExcelPath()
            {
                OpenFileDialog objDialog = MSDialogCollection.GetOpenDialog("xls");
                if (objDialog.ShowDialog() == DialogResult.OK)
                    return objDialog.FileName;
                else
                    return null;
            }
            private DataTable DoImport(string strFileName)
            {
                DataTable objDataTable = MSTextFileProcess.ImportExcelToDataTable(strFileName);
                if (objDataTable == null || objDataTable.Rows.Count == 0) return null;
                return objDataTable;
            }        /// <summary>
            /// HDR=YES DataTable has Column Name,or not.
            /// This function can only import the excel file,which Microsoft Office created.
            /// It can't import the excel file that .NET Framework exported.
            /// </summary>
            /// <param name="strFileName">Imported file detail path</param>
            /// <returns></returns>
            public static DataTable ImportExcelToDataTable(string strFileName)
            {
                if (String.IsNullOrEmpty(strFileName)) return null;
                if (!File.Exists(strFileName)) return null;            OleDbConnection objConn = null;
                OleDbDataAdapter objAdapter = null;
                DataSet objDataSet = null;            try
                {
                    string strConn = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;IMEX=1';", strFileName);
                    objConn = new OleDbConnection(strConn);
                    objConn.Open();
                    string strSql = "SELECT * FROM [sheet1$]";
                    objAdapter = new OleDbDataAdapter(strSql, strConn);
                    objDataSet = new DataSet();
                    objAdapter.Fill(objDataSet);
                }
                catch (Exception ex)
                {
                    return null;
                }
                finally
                {
                    objAdapter.Dispose();
                    objConn.Close();
                }            return objDataSet.Tables[0];
            }以后学着自己动手手试试,给分吧.
      

  15.   

    SELECT * FROM [sheet1$]
    [sheet1$]是什么意思?
      

  16.   

    我也在做这个 不过我觉得还是使用 EXCEL COM组件 一个一个单元格的读到 容器里比较好
    上面提供的这个方法不是很灵活.
      

  17.   

    默认sheet1这个页面啊。这是最简单的,也可以获取页名。将Excel中第一行数据作为datagridview的栏位名            string source = "C:\\a.xls";//execel文件的完整路径
                string sqlconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + source + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1' ";
                OleDbConnection sqlcon = new OleDbConnection(sqlconn);
                sqlcon.Open();
                System.Data.DataTable schemaTable = sqlcon.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
                string tableName = schemaTable.Rows[0][2].ToString().Trim();//获取Excel文件中第一个sheet页的页名。
                string sql = "SELECT  * FROM [" + tableName + "]";
                OleDbCommand oldcom = new OleDbCommand(sql, new OleDbConnection(sqlconn));
                OleDbDataAdapter oleda = new OleDbDataAdapter(oldcom);
                DataSet ds = new DataSet();
                oleda.Fill(ds);
                System.Data.DataTable dtData = new System.Data.DataTable();
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    dtData.Columns.Add(ds.Tables[0].Rows[0][i].ToString());//这里的名字就是自定义的
                    dtData.Columns[i].DefaultValue = ""; //格式化
                }
                DataRow drData;
                for (int i = 1; i < ds.Tables[0].Rows.Count; i++)//过滤相同的值
                {
                    drData = dtData.NewRow();
                    for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                    {
                        drData[j] = ds.Tables[0].Rows[i][j].ToString();
                    }
                    dtData.Rows.Add(drData);
                }
                //dataGridView1.AutoGenerateColumns= false;// 设置不自动增加栏位
                this.dataGridView1.DataSource = dtData;//绑定