PDA

View Full Version : Read Excel file problem


mpls2000
08-02-2004, 11:03 AM
I am able to read data from Microsoft Excel with my ASPNET application. However, I face a problem.

As you can see from my code below, I need to know in advanced the sheet name (Sheet2) of my excel file.

My question is, how should I code my program if I do not know my sheet name in advanced?

Please help. urgent.
Thanks

using System;
using System.Data;
using System.Data.OleDb;


public class example16
{
public static void Main(string[] args)
{
string ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\temp\\data\\jhs.xls;Extended Properties='Excel 8.0;HDR=YES;'";

string SelectString = "SELECT Name, Street, City FROM [Sheet2$]"; //$ can not be omited

using (OleDbConnection myCon = new OleDbConnection(ConnectString) )
{
if (myCon.State != ConnectionState.Open) //if connection is not open, open it
myCon.Open();

Console.WriteLine("Open database successfully!");

OleDbCommand myCmd = new OleDbCommand(SelectString , myCon) ;
OleDbDataReader myReader = myCmd.ExecuteReader();

while (myReader.Read())
{
Console.WriteLine("{0}/{1}/{2}", myReader.GetString(0), myReader.GetString(1), myReader.GetString(2));
}

Console.WriteLine("Read student data successfully!");
myCon.Close();
Console.Read();
}
}
}

Malin
08-06-2004, 06:01 AM
You could take in the name of the sheet as a parameter in "public static void Main(string[] args)"

The string array "args" contains startup parameters used for telling the program variable information like for example sheetname if this is changing from time to time.

But perhaps this is not the solution you are looking for.. you maybe want some solution that tells excel to read from for example sheet number one at all times - not concerning about the name of the sheet? Perhaps this is possible but it still requires your users to always have their sheet as number one in their excel file and that would be difficult for other users than you to remember that (I dont know if your application will be used by others).

If I have understood your question I would probably make a GUI and asking the user for file and sheetname on startup..or if you prefer console I would use the string[] args approach to take in sheetname as startup parameter.

Maybe I have missunderstood you. If so, sorry [:I]