Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to upload excel data but i don't know the sheet name.

What I have tried:

OleDbConnection connection = null;

try
{
    string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'", path);
    connection = new OleDbConnection();
    connection.ConnectionString = excelConnectionString;
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
    connection.Open();
    DbDataReader dr = command.ExecuteReader();
    DataTable table = new DataTable("Customers");
    table.Load(dr);
Posted
Updated 1-Nov-17 3:25am
Comments
Karthik_Mahalingam 1-Nov-17 23:36pm    
refer this C# - Retrieve Excel Workbook Sheet Names.[^] to get the sheeetname and iterate from that.

1 solution

Get the sheet names, and you can find it from there: OleDbConnection.GetOleDbSchemaTable Method (Guid, Object[]) (System.Data.OleDb)[^] - the example MS provide retrieves all sheet names.
 
Share this answer
 
Comments
Member 12962919 1-Nov-17 9:37am    
I used this but this gives me error in query
here is code

OleDbConnection connection = null;

try
{
string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'", path);
connection = new OleDbConnection();
connection.ConnectionString = excelConnectionString;
connection.Open();
DataTable table = new DataTable("Customers");
table = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[table.Rows.Count];
int i = 0;

// Add the sheet name to the string array.
foreach (DataRow row in table.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
string Sheet = excelSheets[1];

string query = "select * from" + Sheet;
OleDbCommand command = new OleDbCommand(query, connection);

DbDataReader dr = command.ExecuteReader();

table.Load(dr);
OriginalGriff 1-Nov-17 9:42am    
And did you use the debugger to look at exactly what was going on?
What did it show you?
Member 12962919 2-Nov-17 0:52am    
The query problem is solved but it add some additional columns in table like Table_catalog,table_schema,table type

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900