C#读取Excel文件到DataTable中

这块代码实现的是根据Excel文件路径,把数据放到DataTalbe中。  

要确保电脑有Office,还有就是可能会报错“未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。”
这个错误只需要下载数据连接组件,也就是下面这个链接可以直接下载安装即可:

http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe

                //excelurl为方法传过来的Excel文件路径
                //fileName获取文件名称和后缀
                string fileName = excelurl.Substring(excelurl.LastIndexOf(@"/") + 1);
                //获取我文件上传的固定地址
                string path = AppDomain.CurrentDomain.BaseDirectory + @"Execls\" + DateTime.Now.ToString("yyyyMMdd") + @"\";
                
                //如果需要把文件保存到另一个路径下可用注释代码    
                //if (!Directory.Exists(path))
                //{
                //    Directory.CreateDirectory(path);
                //}
                //WebClient client = new WebClient();
                //client.DownloadFile(excelurl, path + fileName);

                //源的定义
                string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + fileName + ";" + "Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";
                string strExcel = "select * from [sheet1$]";
                //定义存放的数据表
                DataSet ds = new DataSet();
                //连接数据源
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();

                //适配到数据源
                OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
                adapter.Fill(ds);
                conn.Close();

猜你喜欢

转载自blog.csdn.net/MonkeyBananas/article/details/82985892