使用 OleDb 从 Excel 文档中获取第一张工作表,而不考虑工作表名称

Posted

技术标签:

【中文标题】使用 OleDb 从 Excel 文档中获取第一张工作表,而不考虑工作表名称【英文标题】:Getting the first sheet from an Excel document regardless of sheet name with OleDb 【发布时间】:2009-09-17 10:51:29 【问题描述】:

我有用户为他们的工作表命名各种疯狂的东西,但我希望能够获得 Excel 文档的第一张工作表,而不管它的名字是什么。

我目前使用:

OleDbDataAdapter adapter = new OleDbDataAdapter(
"SELECT * FROM [sheetName$]", connString);

无论第一张纸叫什么,我将如何获得它?

谢谢。

【问题讨论】:

Using Excel OleDb to get sheet names IN SHEET ORDER 的可能重复项 【参考方案1】:

最终使用了这个:

using (OleDbConnection conn = new OleDbConnection(connString))

    conn.Open();
    dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[]  null, null, null, "TABLE" );
    Sheet1= dtSchema.Rows[0].Field<string>("TABLE_NAME");

【讨论】:

【参考方案2】:
OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="Path"; Extended Properties=Excel 12.0;Persist Security Info=False;");

oconn.Open();
myCommand.Connection = oconn;
DataTable dbSchema = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,  null);
if (dbSchema == null || dbSchema.Rows.Count < 1)

    throw new Exception("Error: Could not determine the name of the first worksheet.");

string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();

【讨论】:

根据我的测试,这会按字母顺序返回第一张工作表,而不是根据它们在工作簿中出现的顺序(从左到右)返回的第一张工作表。跨度> 【参考方案3】:

这段代码在我使用数据网格“DataGridView1”加载工作表的所有内容时运行良好

Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet : Dim filteext As String = ""

 ''check for the file type
 If IO.Path.GetExtension(fileName) = "xls" Then
                filteext = "Excel 8.0"
 ElseIf IO.Path.GetExtension(fileName) = ".xlsx" Then
                filteext = "Excel 12.0"
 End If

''open connection

 MyConnection = New System.Data.OleDb.OleDbConnection _
               ("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileName & "';Extended Properties=" & filteext & ";")
            MyConnection.Open()

  Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")

  Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [0]", myTableName), MyConnection)


   MyCommand.TableMappings.Add("Table", "TestTable")
            DtSet = New System.Data.DataSet

    MyCommand.Fill(DtSet)

    DataGridView1.DataSource = DtSet.Tables(0)
            'DtSet.DataSetName. 

    MyConnection.Close()

【讨论】:

【参考方案4】:

这是我的解决方案 ▼(简单、快速、可执行、易懂)

internal static DataTable GetExcelSheet(string excelFile,string sheetName = "")

    string fullPathToExcel = Path.GetFullPath(excelFile);
    string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=0;Extended Properties='Excel " + (excelFile.ToLower().EndsWith("x") ? "12.0" : "8.0") + ";HDR=yes'", fullPathToExcel);
    return GetDataTable(connString, "SELECT * FROM [" + (string.IsNullOrEmpty(sheetName) ? GetTableName(connString, 0) : sheetName + "$") + "]");


private static DataTable GetDataTable(string connectionString, string sql)

    DataTable dt = new DataTable();

    using (OleDbConnection conn = new OleDbConnection(connectionString))
    
        conn.Open();
        using (OleDbCommand cmd = new OleDbCommand(sql, conn))
        
            using (OleDbDataReader rdr = cmd.ExecuteReader())
            
                dt.Load(rdr);
                return dt;
            
        
    

private static string GetTableName(string connectionString, int row = 0)

    OleDbConnection conn = new OleDbConnection(connectionString);
    try
    
        conn.Open();
        return conn.GetSchema("Tables").Rows[row]["TABLE_NAME"] + "";
    
    catch  
    finally  conn.Close();
    return "sheet1";

【讨论】:

【参考方案5】:

基本上是 Anirudh Gaur 答案的副本。我对代码进行了一些重新格式化并将其放入函数中。我添加了一个 StringBuilder,以便我可以使用 SELECT 语句做更多事情。

投票给 Anirudh Gaur

Private Function Load_XLS(FileName As String) As DataTable
    Dim DataTable As New DataTable
    Dim Format As String = ""
    If IO.Path.GetExtension(FileName) = ".xls" Then
        Format = "Excel 8.0"
    ElseIf IO.Path.GetExtension(FileName) = ".xlsx" Then
        Format = "Excel 12.0"
    End If

    Using Connection As New OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & FileName & "';Extended Properties=" & Format & ";")
        Connection.Open()

        Dim TableName As String = Connection.GetSchema("Tables").Rows(0)("TABLE_NAME")

        Dim SQLCommand As New Text.StringBuilder
        SQLCommand.AppendLine("SELECT *")
        SQLCommand.AppendLine("FROM [0]")

        Dim Command As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(String.Format(SQLCommand.ToString, TableName), Connection)

        Command.Fill(DataTable)

        Connection.Close()
    End Using
    Return DataTable
End Function

【讨论】:

【参考方案6】:

您可以使用GetOleDbSchemaTable (VB) 或GetOleDbSchemaTable (C#)。

使用 Tables 枚举,它将返回所有工作表名称的列表,然后您可以使用它来动态构建所需的 SQL。

你可以使用:

MySchemaTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() Nothing, Nothing, Nothing, "TABLE")

所有工作表名称都将作为 DataTable 的一部分返回,您可以对其进行迭代。

使用OleDbSchemaGuid可以检索到信息

列 外键 索引 主键 表格 观看次数

完整的 MSDN 文档可用here

【讨论】:

它看起来像返回一个数据表,我如何获取工作表名称?它是一个命名字段吗? 另外,我要为限制传入什么参数:Object [ ]? @naspinski - 我链接的文章包含所有必需的信息。在过去的 2 年里,我没有与 OLEDB 合作过。如果我没记错的话,表名将在 COLUMN_NAME 字段中。【参考方案7】:

您也可以使用此方法获取工作表名称。更多了解见 cmets

myExcelConn.Open()

//GET DATA FROM EXCEL SHEET.
Dim str As String = String.Empty
Dim Sheets As DataTable = myExcelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
For i As Integer = 0 To Sheets.Rows.Count - 1
    str += Sheets.Rows(i)("TABLE_NAME").ToString() + "," //It will return sheet1,sheet2,sheet3 according to my excel file
Next

Dim objOleDB As New OleDbCommand("SELECT *FROM [" + str.Split(",")(0) + "]", myExcelConn) //It will select sheet1
Me.Label1.Text = str.Split(",")(0).Replace("$", "")
// READ THE DATA EXTRACTED FROM THE EXCEL FILE.
Dim objBulkReader As OleDbDataReader
objBulkReader = objOleDB.ExecuteReader

Dim dt As DataTable = New DataTable
dt.Load(objBulkReader)

//FINALLY, BIND THE EXTRACTED DATA TO THE GRIDVIEW.
GridView1.DataSource = dt
GridView1.DataBind()
//If you want sheet2 data
 Dim objOleDB1 As New OleDbCommand("SELECT *FROM [" + str.Split(",")(1).Split(",")(0) + "]", myExcelConn)
//If you want sheet3 data
 Dim objOleDB2 As New OleDbCommand("SELECT *FROM [" + str.Split(",")(2).Split(",")(0) + "]", myExcelConn)

【讨论】:

您好,请不要只放一大段代码作为答案,还请说明它如何解决用户遇到的问题=)【参考方案8】:

您可以像这样获取 sheet1 名称并以这种方式使用。如果您想获取其他工作表名称,您可以从 0,1,2.. 增加值..

 Dim myExcelConn As OleDbConnection = _
                New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
                    Server.MapPath(".") & "\" & FileUpload1.FileName() & _
                    ";Extended Properties=Excel 12.0;")
    Dim Sheets As DataTable = myExcelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
                Sheet1 = Sheets.Rows(0)("TABLE_NAME").ToString()
  Dim objOleDB As New OleDbCommand("SELECT *FROM [" + Sheet1 + "]", myExcelConn)

【讨论】:

【参考方案9】:

这就是我的解决方案

 private static string GetExcelWorkSheet(string pathToExcelFile)
        
            Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();

            Microsoft.Office.Interop.Excel.Workbook theWorkbook = null;

            theWorkbook = ExcelObj.Workbooks.Open(pathToExcelFile);

            Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;

            // Get the reference of first worksheet. Index start at 1 
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);

            // Get the name of worksheet.
            string strWorksheetName = worksheet.Name; 

            return strWorksheetName;
        

【讨论】:

以上是关于使用 OleDb 从 Excel 文档中获取第一张工作表,而不考虑工作表名称的主要内容,如果未能解决你的问题,请参考以下文章

C# 使用OleDB写数据到excel的插入数据语句!!!

使用 Excel OleDb 在 SHEET ORDER 中获取工作表名称

使用 OLEDB 从 Excel 中读取数据

excel ace.oledb vba 连接到 csv 只返回第一列

使用 OLEDB 适配器从 Excel 表中选择

OleDB读取Myxls生成的Excel文本,结果只能读取到第一列的值