【发布时间】:2015-09-12 05:52:19
【问题描述】:
我正在使用OLEDB 对象读取 Excel 文件并在数据表中返回数据。下面的 Excel 工作表有两列,已导入,但我也想用我的数据读取 Excel 行号。
这是我用来读取 Excel 文件的代码:
private DataTable ImportExcel2007(String strFilePath)
{
if (!File.Exists(strFilePath)) return false;
String strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=" + strFilePath + ";"
+ "Extended Properties='Excel 8.0;HDR=Yes'";
OleDbConnection connExcel = new OleDbConnection(strExcelConn);
OleDbCommand cmdExcel = new OleDbCommand();
try
{
cmdExcel.Connection = connExcel;
//Check if the Sheet Exists
connExcel.Open();
DataTable dtExcelSchema;
//Get the Schema of the WorkBook
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connExcel.Close();
//Read Data from Sheet1
connExcel.Open();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
//Range Query
//cmdExcel.CommandText = "SELECT * From [" + SheetName + "A3:B5]";
da.SelectCommand = cmdExcel;
da.Fill(ds);
connExcel.Close();
return ds.Table[0];
}
catch
{
return null;
}
finally
{
cmdExcel.Dispose();
connExcel.Dispose();
}
}
我可以通过增加数据表中的新列来管理它,但是我可以应用带有 SELECT 语句的 WHERE 子句来返回来自不同行号的数据(应用增加的行号可能会失败)?
【问题讨论】:
标签: c# asp.net .net excel oledb