/// <summary> /// 从Excel文件导入数据 /// </summary> /// <param name="ExcelStr">文件的全路径</param> /// <param name="SheetName">Excel文档里的表名称</param> public static DataSet Class_ExcelSql(string ExcelStr, string SheetName) { OleDbConnection MyConn_E = new OleDbConnection(); OleDbCommand MyComm_E = new OleDbCommand(); OleDbDataAdapter MyAdap = new OleDbDataAdapter(); DataSet MyTable = new DataSet(); if (!File.Exists(ExcelStr)) { DevExpress.XtraEditors.XtraMessageBox.Show("所选文件不存在!", "提示"); return null; } string Conn_Str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelStr + ";Extended Properties='Excel 8.0;HDR=Yes;'"; try { MyConn_E.ConnectionString = Conn_Str; MyConn_E.Open(); MyComm_E.Connection = MyConn_E; MyComm_E.CommandText = "select * from [" + SheetName + "$]"; MyAdap.SelectCommand = MyComm_E; MyAdap.Fill(MyTable); } catch (OleDbException Err_My) { DevExpress.XtraEditors.XtraMessageBox.Show(Err_My.Message, "提示"); } if (MyConn_E.State == ConnectionState.Open) { MyConn_E.Close(); MyConn_E.Dispose(); } MyComm_E.Dispose(); MyAdap.Dispose(); return MyTable; }
其中MyComm_E.CommandText = "select * from [" + SheetName + "$]";抛出异常“"定义了过多字段"”
此问题可以有三种解决办法
办法一:隐藏Excel多余的列开始-格式-隐藏和取消隐藏-选择隐藏列
办法二:把查询语句改为指定开始到结束列
如:"select * from [" + SheetName + "$A:IU]";其中A:IU代表查询第A列到第IU列。
办法三:查询指定列
如:"select 第一列,第二列 from [" + SheetName + "$]";。
以上三种方法都可以解决“定义了过多字段”