读取EXCEL的时候,老是说定义了过多的字段,但有的时候又没问题.这种有时好有时坏的毛病最让人恼火.后来我发现,给他定义一个RANGE,它就不会不错了.但是我要读的是全部呀,不是一个RANGE, 没办法,理论上说我用的的文件不会超过500行,于是给它来个RANGE,读到500行,居然就可以了,就算你的文件只有几行也没问题.
string xls = fileName;
InitializeComponent();
string dbpath = xls;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dbpath + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection OleDbConnection = new OleDbConnection(strConn);
OleDbConnection.Open();
DataTable dtSchema = OleDbConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
OleDbConnection.Close();
string tableName = dtSchema.Rows[0][2].ToString().Trim();
MessageBox.Show(tableName);
OleDbCommand OleDbCommand = new OleDbCommand("SELECT * FROM [" + tableName + "A1:AB500]", OleDbConnection);
OleDbDataAdapter oa = new OleDbDataAdapter(OleDbCommand);
oa.FillSchema(dt, SchemaType.Source);
oa.Fill(dt);
oa.FillSchema(dt2, SchemaType.Source);
oa.Fill(dt2);
RemoveEndEmptyLines(ref dt2, dt2.Rows.Count - 1);
dt2.Rows.RemoveAt(0);
dataGridView1.DataSource = dt2;
--
Feng
string xls = fileName;
InitializeComponent();
string dbpath = xls;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dbpath + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection OleDbConnection = new OleDbConnection(strConn);
OleDbConnection.Open();
DataTable dtSchema = OleDbConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
OleDbConnection.Close();
string tableName = dtSchema.Rows[0][2].ToString().Trim();
MessageBox.Show(tableName);
OleDbCommand OleDbCommand = new OleDbCommand("SELECT * FROM [" + tableName + "A1:AB500]", OleDbConnection);
OleDbDataAdapter oa = new OleDbDataAdapter(OleDbCommand);
oa.FillSchema(dt, SchemaType.Source);
oa.Fill(dt);
oa.FillSchema(dt2, SchemaType.Source);
oa.Fill(dt2);
RemoveEndEmptyLines(ref dt2, dt2.Rows.Count - 1);
dt2.Rows.RemoveAt(0);
dataGridView1.DataSource = dt2;
--
Feng
1 条评论:
发生这种情况的原因是你把所有行,列都格式化了,我的解决方法是干脆放到最大行65535.
发表评论