GetExcelSheetNames:
static String[] GetExcelSheetNames(string excelFile, string extention)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
string filepath= excelFile;// +; excelFile;
string Conn = "";
if (extention == "xls")
Conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath+ ";Extended Properties=Excel 8.0;";
else Conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath+ ";Extended Properties=Excel 12.0";
try
{
// Connection String. Change the excel file to the file you
// will search.
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(Conn);
// Open connection with the database.
objConn.Open();
// Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
GetTable:
private DataSet GetTable(string filepath, string extention)
{
string strConn;
if (extention == "xls")
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
}
else
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0";
}
DataSet myDataSet = new DataSet();
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [" + GetExcelSheetNames(filepath, extention)[0] + "]", strConn);
myCommand.Fill(myDataSet, "ExcelInfo");
if (myDataSet.Tables[0].Rows.Count > 0)
{
return myDataSet;
}
else return null;
}
我使用OleDbDataAdapter将 excel数据导出到数据表。
我的两种方法(上方)都有效但最后一行缺失。
我完全错过了如何从excel获取所有行?
任何帮助将不胜感激。
感谢。