Tuesday, March 3, 2009

How to read the first sheet in Excel with C#


string AppPath=Request.ServerVariables["APPL_PHYSICAL_PATH"]+"Tahsilat/";
OleDbConnection m_ConnectionToExcelBook;
OleDbDataAdapter m_AdapterForExcelBook;
m_ConnectionToExcelBook = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+AppPath+"deneme.xls;Extended Properties=Excel 8.0;");
bool ErrorExist=false;

try
{

m_ConnectionToExcelBook.Open();
DataTable dtExcelSchema = m_ConnectionToExcelBook.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// select first sheetname
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
DataTable DataObject = new DataTable();
OleDbCommand selectCommand = new OleDbCommand("select * from [" + sheetName + "]");


selectCommand.Connection = m_ConnectionToExcelBook;
m_AdapterForExcelBook = new OleDbDataAdapter();
m_AdapterForExcelBook.SelectCommand = selectCommand;
m_AdapterForExcelBook.Fill(DataObject);

if (DataObject.Rows.Count > 0)
{
.......
.......
}

No comments: