从Excel获取工作表名称

时间:2015-02-09 14:36:09

标签: c# sql-server excel

我正在将Excel文件上传到SQL Server数据库。我目前正在使用此行从表单中获取数据:

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

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

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

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