C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Forums » .NET » Windows »

To add the contents of a selected excel file to the datagridview.


Posted Date: 01 Nov 2009      Posted By: Dhanya       Member Level: Silver     Points: 1   Responses: 2



I want to add the contents of an excel file to my datagrid view using C# code.Also I'm using Asp.net2.0& MSOffice 2007.Please help me in doing this.





Responses

Author: vipul    01 Nov 2009Member Level: DiamondRating: 2 out of 52 out of 5     Points: 2

hi,
for the reading excel file you can used this way
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("G2BResultList.xls") + ";" +
"Extended Properties=Excel 8.0;";
OleDbConnection con = new OleDbConnection(strConn);
con.Open();
if (con.State == ConnectionState.Open)
{
OleDbDataAdapter adp = new OleDbDataAdapter("Select * From [G2BResults$A2:K13]", con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
if (dsXLS.Tables.Count > 0)
{
foreach (DataRow drData in dsXLS.Tables[0].Rows)
{
}}}

Please Rate This Answer If They Helpful

Thanks & Regards
Patel Vipul



Author: Dhanya     01 Nov 2009Member Level: SilverRating: 2 out of 52 out of 5     Points: 2

Hai vipul,

Thank you for your response.Here I want to open both the .xls & .xlsx files.How can I open both these files.
I will paste here my code.please check it..


public void setExcelFileAsDataSourceToDataGridView(string FileName)
{
OleDbConnection objConn;
OleDbDataAdapter oleDA;
DataSet ds; //Check Whether file is xls file or not
if (Path.GetExtension(FileName) == ".xlsx")
{
try
{
//Create a OLEDB connection for Excel file
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + FileName + ";" + "Extended Properties=Excel 8.0;";

objConn = new OleDbConnection(connectionString);
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();

oleDA = new OleDbDataAdapter("select * from []", objConn);
ds = new DataSet();
//Fill the Data Set
oleDA.Fill(ds);
//Set DataSource of DataGridView
dataGridView1.DataSource = ds.Tables[0];
ds.Dispose();
oleDA.Dispose();
}
objConn.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Please select Excel File");
}
}



Post Reply
You must Sign In to post a response.
Next : How to get data from a merged xml file?
Previous : to open both the .xls & .xlsx files.
Return to Discussion Forum
Post New Message
Category: Windows

Related Messages



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use