Click here to Skip to main content
15,895,656 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have some code here and it is stumping me. I have an Excel file that I am trying to process, when I try to access a column in a row I don't get any data. Any help would be appreciated:

MSIL
try
           {
               OleDbConnection ExcelConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + txtFileName.Text + "'" + ";Extended Properties=Excel 8.0;");
               OleDbDataAdapter ExcelCommand = new OleDbDataAdapter("select * from [Contacts$]", ExcelConnection);
               ExcelCommand.Fill(dtExcel, "Excel");
               ExcelConnection.Close();
               if (ValidRec()) CrtNwRecords();
               else MessageBox.Show("Errors Exist in Spreadsheet");
           }
           catch(Exception ex)
           {
               MessageBox.Show(ex.ToString());
           }
       }
       private bool ValidRec()
       {
           for (int x = 0; x < dtExcel.Tables[0].Rows.Count; x++)
           {
               if (dtExcel.Tables[0].Rows[x][0].ToString() == "") MessageBox.Show(dtExcel.Tables[0].Rows[x][0].ToString()); //First Name
           }
           return true;
       }


Posted

1 solution

This worked for me:

C#
OleDbConnection ExcelConnection = new OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\temp\excel_data_file.xls';Extended Properties=Excel 8.0;");
OleDbDataAdapter ExcelCommand = new OleDbDataAdapter("select * from [Tabelle1$]", ExcelConnection);
DataTable dtExcel = new DataTable("is_wuascht");
ExcelCommand.Fill(dtExcel);

Console.WriteLine("list of column names");
Console.WriteLine("column name: " + dtExcel.Columns[0].ColumnName);
Console.WriteLine("column name: " + dtExcel.Columns[1].ColumnName);

Console.WriteLine("row data"); 
foreach (DataRow dr in dtExcel.Rows)
{
   Console.WriteLine("Row: " + dr[0].ToString() + ":" + dr[1].ToString());
}
 
Share this answer
 
v2
Comments
Nuri Ismail 19-Aug-10 5:47am    
I've added PRE tags for the code snippet. A good call anyway, have a 5! :)
Dalek Dave 19-Aug-10 5:52am    
Yeah, Good Answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900