简体   繁体   English

如何使用OleDbDataAdapter从Excel文件中的任何电子表格中进行选择

[英]How to SELECT from any spreadsheet in Excel File using OleDbDataAdapter

I'm using OleDbDataAdapter to extract DataSet from excel file, but I have problems with SELECT statement inside 我正在使用OleDbDataAdapter从excel文件中提取DataSet ,但我的SELECT语句里面有问题

DataSet excelDataSet = new DataSet();
using (OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString))
{
     con.Open();
     OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter("select * from [Name of spreadsheet]", con);
     cmd.Fill(excelDataSet);
     con.Close();
}

If you see I have "select * from [Name of spreadsheet]" , but I need to get any spreadsheets, or for example 1st spreadsheet, but the name for this spreadsheet can be anything. 如果您看到我"select * from [Name of spreadsheet]" ,但我需要获取任何电子表格,例如第一个电子表格,但此电子表格的名称可以是任何内容。

How to specify it? 怎么指定呢? Is it any special characters like "select * from [%]" 是否有任何特殊字符,例如"select * from [%]"

You need to know the name of the sheet to apply the select statement at it. 您需要知道要在其上应用select语句的工作表名称。
And you need to add the special char $ at the end of the name. 并且您需要在名称末尾添加特殊的char $

Supposing you have a sheet named MyFirstSheet then you can select rows from it with 假设您有一个名为MyFirstSheet的工作表,那么您可以从中选择行

 OleDbDataAdapter cmd = new OleDbDataAdapter("select * from [MyFirstSheet$]", con);

In case you don't know the names of your sheets you could call 如果你不知道你可以打电话的床单名称

using (OleDbConnection con = new OleDbConnection(connectionString))
{
    con.Open();
    DataTable dt = con.GetSchema("Tables");
    string firstSheet = dt.Rows[0]["TABLE_NAME"].ToString();
    ...... work with the first sheet .....
}

This example should give you the name of the first sheet in the excel file (other sheets are available in the successive rows after the first) 此示例应该为您提供excel文件中第一个工作表的名称(其他工作表在第一个工作表之后的连续行中可用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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