C#获取Excel里sheet名,其表内容

  1. public static DataTable GetExcelTable(string excelFilename)  
  2. {  
  3.     string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=35;Extended Properties=Excel 8.0;Persist Security Info=False",excelFilename);  
  4.     DataSet ds = new DataSet();  
  5.     string tableName;  
  6.     using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connectionString))  
  7.     {  
  8.         connection.Open();  
  9.         DataTable table = connection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);  
  10.         tableName = table.Rows[0]["Table_Name"].ToString();  
  11.         string strExcel = "select * from " + "[" + tableName + "]";  
  12.         OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, connectionString);  
  13.         adapter.Fill(ds, tableName);  
  14.         connection.Close();  
  15.     }  
  16.     return ds.Tables[tableName];  
  17. }
  18.   //VB Code
  19.     Dim connectionString As String ' Used to store the connection string

        Dim customerList As New DataSet ' Used to store the temp records readed from the Excel file

        Dim excelData As OleDb.OleDbDataAdapter

     

        connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=YES"";", fileName)

        excelData = New OleDb.OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString)

        excelData.TableMappings.Add("Sheet1", "ImportCustomer")

    excelData.Fill(customerList)

posted on 2010-11-08 16:07  瑞德  阅读(9775)  评论(0编辑  收藏  举报

导航