简体   繁体   中英

Getting Sheet Name From Excel

I am uploading excel files to a SQL Server database. I am currently using this line to get the data from the sheet:

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

The problem is, if the sheet name isn't Sheet1 then it will fail. Is there a way to get the sheet name rather than hard coding in Sheet1 ?

You can query the schema first using GetOleDbSchemaTable :

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

The name of the first table should be at schemaTable.Rows[0][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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM