i




 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading Excel file data using c#
08-20-2011, 04:21 PM
Post: #1
Reading Excel file data using c#
You can query the excel file same as you query the sql database.


first write the using statement
Code:
using System.Data.Common;


then you can write normal sql queries to query the excel file

Remember that just like in the sql table there are column name and then the table date same applies to the excel first row contains the name of column and then next rows contain the table data. Your sheet Name is the name of your table.



Code:
string FileName="t.xls";
            string constring ="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");

            using (DbConnection connection = factory.CreateConnection())
            {
                connection.ConnectionString = constring;

                using (DbCommand command = connection.CreateCommand())
                {

                    command.CommandText="Select * from [mys$]";
                
                    //connection.Open();
                    
                   // DbDataReader dr= command.ExecuteReader();

                    DataTable dt = new DataTable();
                    DbDataAdapter da = factory.CreateDataAdapter();
                    da.SelectCommand = command;
                   da.Fill(dt);

                  dataGridView1.DataSource = dt;

                }
            }

In the code above mys is the name of the sheet and you have to write the column name in correct format.

Example:-
[mytblName$]


Quote
08-22-2011, 07:09 AM
Post: #2
RE: Reading Excel file data using c#
congrats hyder ali
Quote
12-06-2011, 12:18 PM
Post: #3
RE: Reading Excel file data using c#
its good but if the execl sheet has name change then its code give error
so plese find excel sheet then do this code
Quote
12-06-2011, 04:51 PM
Post: #4
RE: Reading Excel file data using c#
then replace your sheet name with mys e.g.

[mys$] -> [sheetrename$]
Quote


Possibly Related Threads...
Thread: Author Replies Views: Last Post
  Reading Dicom File in C#.net gopal213 1 6,226 10-12-2010 11:40 AM
Last Post: arti.porwal20@gmail.com



User(s) browsing this thread: 1 Guest(s)