Windows Develop Bookmark and Share   
 index > Windows Forms General > Import Excel file into dataGridView
 

Import Excel file into dataGridView

Hi All,

I am trying to use the following code (from another post)to import excel into my application and then dislplay the results in a dataGridview

private void button1_Click(object sender, EventArgs e)
{
DataTable test = getDataFromXLS("c:\temp.xls");
if (test != null)
dataGridView1.DataSource = test;
}


private DataTable getDataFromXLS(string strFilePath)
{
try
{
string strConnectionString = "";
strConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + strFilePath + "; Jet OLEDB:Engine Type=5;" +
"Extended Properties=Excel 8.0;";
OleDbConnection cnCSV = new OleDbConnection(strConnectionString);
cnCSV.Open();
OleDbCommand cmdSelect = new OleDbCommand(@"SELECT * FROM [Sheet1$]", cnCSV);
OleDbDataAdapter daCSV = new OleDbDataAdapter(); daCSV.SelectCommand = cmdSelect;
DataTable dtCSV = new DataTable();
daCSV.Fill(dtCSV);
cnCSV.Close();
daCSV =
null;
return dtCSV;
}
catch (Exception ex)
{
return null;
}
finally { }
}

My problem is, it is doing absolutely nothing .. no errors no nothing ...

Do I need to register/enable OLEDB on my local machine? Or is this included/enabled in the .Net framework...

any suggestions would be greatly appreciated...

thanks,

Paul

dn8  Tuesday, October 23, 2007 8:59 PM

Figured it out .. something simple of course.. My "Sheet1" isn't name sheet one at all .. it's named testes!

-P

dn8  Wednesday, October 24, 2007 2:18 AM
well, it probably throws an exception that's caught and return null. why not debug into the code and see which line causes the problem?
H. _冬_ Tony  Tuesday, October 23, 2007 9:29 PM

shouldn't the line

catch (Exception ex)

throw and exception?

I am running in debug and it is not showing any exceptions... however the data table is coming back as null

I changed the code from

if (test != null)

to

if (test == null) {

MessageBox.Show("nada");

}

and I am prompted with "nada"

so that is why I was wondering if the driver needed to be enabled/installed

Paul

dn8  Tuesday, October 23, 2007 9:37 PM

Figured it out .. something simple of course.. My "Sheet1" isn't name sheet one at all .. it's named testes!

-P

dn8  Wednesday, October 24, 2007 2:18 AM

You can use google to search for other answers

Custom Search

More Threads

• MessageBox not given Focus
• Listview scrolling
• ComboBox item backcolor?
• ie cert
• C# bring windows SDI form to front of all other forms
• ProcessCmdKey and Controls.Clear
• Can I bind a combobox list to a User Setting ?
• Can't drag-drop a link from a webbrowser control or IE
• WebBrowser Url IP?
• Setting the Caret Position in a MaskedTextBox / TextBox