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