我使用以下代码来阅读Excel工作表。将使用此代码的工作簿将只有一个工作表。工作表名称可能会更改,但我只是希望能够在默认情况下读取第一个工作表的名称。如果可能,如何实现这一目标?
if (fileName != string.Empty)
{
string connString = "";
System.Data.DataTable dt = new System.Data.DataTable();
// Initialize connection string
connString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\"", fileName);
// Connect
OleDbConnection myConnection = new OleDbConnection(connString);
// Open connection if closed
if (myConnection.State != ConnectionState.Open)
myConnection.Open();
string sql = "SELECT * from [INTKEAP_INV_DST_48$]";
OleDbCommand cmd = new OleDbCommand(sql, myConnection);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(dt);
......... 任何帮助表示赞赏。
答案 0 :(得分:2)
我的代码片段,包括更谨慎的资源处理:
const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\"Excel 8.0;HDR=no;\";";
OleDbConnection objConnection = new OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fullFileName));
DataSet dsImport = new DataSet();
try
{
objConnection.Open();
DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if( (null != dtSchema) && ( dtSchema.Rows.Count > 0 ) )
{
string firstSheetName == dtSchema.Rows[0]["TABLE_NAME"].ToString();
new OleDbDataAdapter("SELECT * FROM [" + firstSheetName + "]", objConnection).Fill(dsImport);
}
catch
{
throw;
}
finally
{
// Clean up.
if(objConnection != null)
{
objConnection.Close();
objConnection.Dispose();
}
}
return (dsImport.Tables.Count > 0) ? dsImport.Tables[0] : null;