【问题标题】:Getting Sheet Name From Excel从 Excel 获取工作表名称
【发布时间】:2015-02-09 14:36:09
【问题描述】:

我正在将 excel 文件上传到 SQL Server 数据库。我目前正在使用这一行从工作表中获取数据:

string myQuery = "Select * from [Sheet1$]";

问题是,如果工作表名称不是Sheet1,那么它将失败。有没有办法在Sheet1 中获取工作表名称而不是硬编码?

【问题讨论】:

    标签: c# sql-server excel


    【解决方案1】:

    您可以先使用GetOleDbSchemaTable查询架构:

    DataTable schemaTable = connection.GetOleDbSchemaTable(
        OleDbSchemaGuid.Tables,
        new object[] { null, null, null, "TABLE" });
    

    第一个表的名称应该是schemaTable.Rows[0][0]

    【讨论】:

      【解决方案2】:
      Function GetSheetNames(ByVal ExcelFile As String) As List(Of String)
          Dim _Sheets As Sheets = Nothing
          Dim LstSheetName As List(Of String) = Nothing
          Try
              LstSheetName = New List(Of String)
              Using Document As SpreadsheetDocument = SpreadsheetDocument.Open(ExcelFile, False)
                  Dim _WorkbookPart As WorkbookPart = Document.WorkbookPart
                  _Sheets = _WorkbookPart.Workbook.Sheets
              End Using
      
              For Each Item As Sheet In _Sheets
                  LstSheetName.Add(Item.Name)
              Next
              Return LstSheetName
          Catch ex As Exception
              Throw ex
          End Try
      End Function
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多