首页 > 代码库 > C# 读表方式读取Excel数据
C# 读表方式读取Excel数据
效果图:
相关引用:
using System.Data; using System.Data.OleDb;
方法源码:
/// <summary> /// 读取EXCEL列数据 /// </summary> /// <param name="excel_path">要读取的Excel路径</param> /// <param name="select_field">要读取的列名</param> /// <param name="sheet_name">读取sheet页</param> /// <param name="range">读取区域</param> /// <param name="where_field">条件列名</param> /// <param name="where_condition">条件值列表</param> /// <returns></returns> public static DataTable LoadDataFromExcel(string excel_path, string select_field, string sheet_name, string range, string where_field, string[] where_condition) { //定义并根据Excel版本确定链接字符串 var file = new System.IO.FileInfo(excel_path); var strConn = string.Empty; switch (file.Extension) { case ".xls": strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excel_path + ";Extended Properties=‘Excel 8.0;HDR=Yes;IMEX=1;‘"; break; case ".xlsx": strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel_path + ";Extended Properties=‘Excel 12.0;HDR=Yes;IMEX=1;‘"; break; default: strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel_path + ";Extended Properties=‘Excel 12.0;HDR=Yes;IMEX=1;‘"; break; } OleDbConnection OleConn = new OleDbConnection(strConn); OleConn.Open(); //确定要读取的列名 var strSelectCol = string.IsNullOrWhiteSpace(select_field) ? "*" : select_field.Trim(); //拼接query语句 var sql = "SELECT " + strSelectCol + " FROM [" + sheet_name +"$"+ range + "]"; for (int i = 0; i < where_condition.Length; i++) { sql += (i == 0 ? " WHERE " : " or ") + where_field + " like ‘%" + where_condition[i] + "%‘"; } //读取数据 OleDbDataAdapter Oleda = new OleDbDataAdapter(sql, OleConn); DataSet Oleds = new DataSet(); Oleda.Fill(Oleds, sheet_name); OleConn.Close(); return Oleds.Tables[0]; }
C# 读表方式读取Excel数据
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。