1

我有以下代码用于阅读 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);

......... 任何帮助表示赞赏。

4

1 回答 1

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;
于 2013-06-04T12:50:15.843 回答