无论使用OleDb的工作表名称,从Excel文档获取第一张工作表

时间:2009-09-17 10:51:29

标签: .net oledb

我有用户为他们的表单命名各种疯狂的东西,但我希望能够获得Excel文档的第一张,无论它的名称是什么。

我目前使用:

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

无论名称是什么,我如何获得第一张?

谢谢。

9 个答案:

答案 0 :(得分:27)

最终使用了这个:

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");
}

答案 1 :(得分:15)

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();

答案 2 :(得分: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()

答案 3 :(得分:1)

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

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

您可以使用:

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

所有工作表名称将作为DataTable的一部分返回,您可以通过它们进行迭代。

可以在

上检索使用OleDbSchemaGuid信息
  
      
  •   
  • 外键
  •   
  • 索引
  •   
  • 主键
  •   
  •   
  • 浏览
  •   

完整的MSDN文档here

答案 4 :(得分:1)

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

Upvotes转到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

答案 5 :(得分:1)

这是我的解决方案▼(轻松,快速,可执行,可理解)

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";
}

答案 6 :(得分:0)

您也可以使用这种方法来获取工作表名称。查看评论以获取更多了解

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)

答案 7 :(得分:0)

您可以像这样获取工作表1名称并以这种方式使用。如果要获取其他工作表名称,则可以从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)

答案 8 :(得分:0)

那是我的解决方法

c.print("How many lines do you want in the histogram? ");
int max = c.readInt();
//declare array of the same size, catch exception if user inputs string

int[] totalSize = new int[max];
int x = 0;
int y = 0;
//store all the values in total size array.
for (int i = 0; i < max; i++) {
 c.print("Type in the value for this line: ");
 double num = c.readDouble();
 y = (int) Math.round(num);
 totalSize[i] = y;
}
//print all the values at once;
for (int i = 0; i < max; i++) {
 x = 0;
 y = totalSize[i];
    while (x < y) {
      c.print("*");
      x++;
    }
 c.println(num);
}