代码如下:
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =1.xls;Extended Properties='Excel 8.0;IMEX=1;HDR=NO;'";
OleDbConnection odcConnection = new OleDbConnection(strCon);
odcConnection.Open(); System.Data.DataTable _Table = odcConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
List<string> sheetNames = new List<string>();
for (int i = 0; i < _Table.Rows.Count; i++)
{
sheetNames.Add(_Table.Rows[i]["Table_Name"].ToString());
} foreach (string sheet in sheetNames)
{
if (!sheet.EndsWith("$"))
continue; OleDbCommand odCommand = odcConnection.CreateCommand();
odCommand.CommandText = "SELECT * FROM ["+sheet+"]";
OleDbDataReader odrReader = odCommand.ExecuteReader();
int size = odrReader.FieldCount; int rowIdx = 0; while (odrReader.Read())
{
for (int colIdx = 0; colIdx < size; colIdx++)
{
string cellValue = odrReader[colIdx].ToString();
} rowIdx++; }
}
}当访问一些excel文件时得到了
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dllAdditional information: 定义了过多字段。这个异常。请高手指导,如何解决这个问题?
据我目前在网上搜索的结果,好像说这个问题在于excel文件中存在过多的空白列。目前的环境是,excel文件是不能修改的,因此不能通过打开excel文件把所有的多余的空白删除。请指导,是否在程序的角度上有办法解决这个问题?谢谢
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =1.xls;Extended Properties='Excel 8.0;IMEX=1;HDR=NO;'";
OleDbConnection odcConnection = new OleDbConnection(strCon);
odcConnection.Open(); System.Data.DataTable _Table = odcConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
List<string> sheetNames = new List<string>();
for (int i = 0; i < _Table.Rows.Count; i++)
{
sheetNames.Add(_Table.Rows[i]["Table_Name"].ToString());
} foreach (string sheet in sheetNames)
{
if (!sheet.EndsWith("$"))
continue; OleDbCommand odCommand = odcConnection.CreateCommand();
odCommand.CommandText = "SELECT * FROM ["+sheet+"]";
OleDbDataReader odrReader = odCommand.ExecuteReader();
int size = odrReader.FieldCount; int rowIdx = 0; while (odrReader.Read())
{
for (int colIdx = 0; colIdx < size; colIdx++)
{
string cellValue = odrReader[colIdx].ToString();
} rowIdx++; }
}
}当访问一些excel文件时得到了
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dllAdditional information: 定义了过多字段。这个异常。请高手指导,如何解决这个问题?
据我目前在网上搜索的结果,好像说这个问题在于excel文件中存在过多的空白列。目前的环境是,excel文件是不能修改的,因此不能通过打开excel文件把所有的多余的空白删除。请指导,是否在程序的角度上有办法解决这个问题?谢谢
结果是依然会有同样的异常抛出
using(OleDbConnection odcConnection = new OleDbConnection(strCon))
{
//TODO
}还有就是Office确实对行数和列数有限制,但是估计你也到不了那么多的列可以输出看看到底有多少列?是不是所有空数据都算了啊
另外可以断点测试一下,
看看多出了什么东西.
关键是看有些什么东西在里面.
DataSet ds = new DataSet();
using(OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
string str = "select * from [sheet1$]";
OleDbDataAdapter da= new OleDbDataAdapter(str, conn);
da.Fill(ds);
conn.Close();
}
设置相关格式
HDR只是设置读取excel的时候第一行是当成数据读还是当成字段名来读
这么说,访问的excel文件中的信息是凌乱的,都是用户自定义的一些表格/图标/数据等。
在开起,用后在关,在查下吧。
因此在查询时odCommand.CommandText = "SELECT * FROM ["+sheet+"A:IU]";
行数应该也有限制。但是行数限制要比列数宽松。这里就没有对行做限制。
这样暂时就解决问题了。结贴咯。