Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 118,862 C# Programmers for FREE! Ask your question and get quick answers from experts. There are 1,690 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



How to access Excel sheet using C#

 
Reply to this topicStart new topic

How to access Excel sheet using C#, I am working on a project to acess excel sheet between certain keywor

plenitude
post 4 Jul, 2008 - 05:28 AM
Post #1


New D.I.C Head

*
Joined: 4 Jul, 2008
Posts: 8

Unhandled Exception: System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed
FYI:It is console based C# project,also currently I am at abeginner level,so just trying to open an XLS sheet an trying to read it smile.gif
CODE


using System;

using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;


namespace Excelcalling1
{
    class Program
    {
        static void Main(string[] args)
        {
            string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;
                    Data Source=E:\SheetForTest.xls;Integrated Security=SSPI;
                    Extended Properties=Microsoft Excel 11.0 Object Library";

            //Create the connection

            System.Data.OleDb.OleDbConnection ExcelConnection =
            new System.Data.OleDb.OleDbConnection
                             (ConnectionString);

            //create a string for the query

            string ExcelQuery;

            //Sheet1 is the sheet name
            //create the query:
            //read column with heading A from the Excel file

            ExcelQuery = "Select A from [Sheet1$]"; // from Sheet1";

            //use "Select * ... " to select the entire sheet
            //create the command

            System.Data.OleDb.OleDbCommand ExcelCommand = new System.Data.OleDb.OleDbCommand(ExcelQuery, ExcelConnection);

            //Open the connection

            //ExcelConnection.Open();
            try
            {
                ExcelConnection.Open();
            }
            catch (OleDbException e)
            {
                string errorMessages = "";

                for (int i = 0; i < e.Errors.Count; i++)
                {
                    errorMessages += "Index #" + i + "\n" +
                                     "Message: " + e.Errors[i].Message + "\n" +
                                     "NativeError: " + e.Errors[i].NativeError + "\n" +
                                     "Source: " + e.Errors[i].Source + "\n" +
                                     "SQLState: " + e.Errors[i].SQLState + "\n";
                }

                System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
                log.Source = "My Application";
                log.WriteEntry(errorMessages);
                Console.WriteLine("An exception occurred. Please contact your system administrator.");
            }

            //Create a reader

            System.Data.OleDb.OleDbDataReader ExcelReader;
            ExcelReader = ExcelCommand.ExecuteReader();

            //For each row after the first
            //Message box the values in the first column i.e. column 0

            while (ExcelReader.Read())
            {
                //MessageBox.Show((ExcelReader.GetValue(0)).ToString());
                Console.WriteLine("value retrieved!!");
            }
            ExcelConnection.Close();

            
        }
    }
}






Thanx in advance smile.gif
User is offlineProfile CardPM

Go to the top of the page


tody4me
post 9 Jul, 2008 - 12:56 PM
Post #2


Only Jenny Craig makes thin clients...

Group Icon
Joined: 12 Apr, 2006
Posts: 1,074



Thanked 3 times

Dream Kudos: 100
My Contributions


You need to install the PIA from Microsoft for the version of Office that is installed on the computer. The you just need to create a workbook object, an application object, and, if you want to get the data from a workbook, a worksheet object. Use those to open, close, and retrieve data from an excel spreadsheet.

This post has been edited by tody4me: 9 Jul, 2008 - 12:56 PM
User is offlineProfile CardPM

Go to the top of the page

plenitude
post 17 Jul, 2008 - 12:24 AM
Post #3


New D.I.C Head

*
Joined: 4 Jul, 2008
Posts: 8

Hi,
Thanx 4 reply bt I solved my problem with out downloading anything.But my soln can read excel sheet using query.


The code goes this way:-


CODE

using System;

using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;

//using Microsoft Office Excel 2003 11.0;
//using Excel;

namespace Excelcalling1
{
    class Program
    {
        static void Main(string[] args)
        {

                        string F1Name = "E:\\SheetForTest.xls";

                        string CnStr = ("Provider=Microsoft.Jet.OLEDB.4.0;" + ("Data Source="

                        + ( F1Name + (";" + "Extended Properties=\"Excel 8.0;\""))));

                        DataTable DT = new DataTable();

                        OleDbDataAdapter DA = new OleDbDataAdapter("Select * from [Sheet1$]", CnStr);

                        Console.WriteLine("File Accessed!!!!");

                try

                {  

                    DA.Fill(DT);

                    //dataGridView1.DataSource = DT;

                }

                catch (Exception ex)

                {

                    Console.WriteLine(ex.Message);

                }

              

        }
    }
}



Note:You need to to do settings in Project>Add reference>Microsoft oject 11.0 library & Microsoft Excel 11.0 for this code to work.

I am not knowing how to find/query for a particular string in the excel sheet.

My aim is to select a part of excel(vertically) b/w two specific strings n read selected part.

Please reply in simple terms as I am new to programming

Any soln from scratch will also do or an extension to what I have already done




User is offlineProfile CardPM

Go to the top of the page

Redian
post 17 Jul, 2008 - 04:53 PM
Post #4


New D.I.C Head

*
Joined: 28 Dec, 2007
Posts: 21

QUOTE(plenitude @ 17 Jul, 2008 - 12:24 AM) *

Hi,
Thanx 4 reply bt I solved my problem with out downloading anything.But my soln can read excel sheet using query.


The code goes this way:-


CODE

using System;

using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;

//using Microsoft Office Excel 2003 11.0;
//using Excel;

namespace Excelcalling1
{
    class Program
    {
        static void Main(string[] args)
        {

                        string F1Name = "E:\\SheetForTest.xls";

                        string CnStr = ("Provider=Microsoft.Jet.OLEDB.4.0;" + ("Data Source="

                        + ( F1Name + (";" + "Extended Properties=\"Excel 8.0;\""))));

                        DataTable DT = new DataTable();

                        OleDbDataAdapter DA = new OleDbDataAdapter("Select * from [Sheet1$]", CnStr);

                        Console.WriteLine("File Accessed!!!!");

                try

                {  

                    DA.Fill(DT);

                    //dataGridView1.DataSource = DT;

                }

                catch (Exception ex)

                {

                    Console.WriteLine(ex.Message);

                }

              

        }
    }
}



Note:You need to to do settings in Project>Add reference>Microsoft oject 11.0 library & Microsoft Excel 11.0 for this code to work.

I am not knowing how to find/query for a particular string in the excel sheet.

My aim is to select a part of excel(vertically) b/w two specific strings n read selected part.

Please reply in simple terms as I am new to programming

Any soln from scratch will also do or an extension to what I have already done


all you have to do is create an oledb command object, with the sql query command...I know it sounds complicated, but its not that hard, I'm doing the exact same thing, see these articles:
http://www.csharp-station.com/Tutorials/Ad...t/Lesson01.aspx

Its how I ended up understanding it all. Let me know if you get around the problem I'm having though: I can't get it to create a spreadsheet outside of the directory of the executable.
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 10/13/08 01:49AM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month