怎么把一个excel导入到winform的dataGridView中

.Net技术 码拜 9年前 (2016-03-01) 1287次浏览
不使用数据库   直接就是将excel导入到dataGridView中而已   哪位高手发下代码呀
解决方案

40

调用: EcxelToDataGridView("test.xls",dataGridView1);
  /// Excel数据导入方法
        public void EcxelToDataGridView(string filePath,DataGridView dgv)
        {
            //根据路径打开一个Excel文件并将数据填充到DataSet中
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + filePath + ";Extended Properties ="Excel 8.0;HDR=NO;IMEX=1"";//HDR=YES 有两个值:YES/NO,表示第一行能否字段名,默认是YES,第一行是字段名
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataSet ds = null;
            strExcel = "select  * from   [sheet1$]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds = new DataSet();
            myCommand.Fill(ds, "table1");
            dataGridView1.DataSource = ds.Tables[0].DefaultView; 
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎么把一个excel导入到winform的dataGridView中
喜欢 (0)
[1034331897@qq.com]
分享 (0)