ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

C# program that interfaces with MS Excel: Conduct a simple SEARCH operation on an Excel file

Updated on October 15, 2009

1.    Open a new Visual C# .NET windows application. Name the project SearchExcel.
2.    In Solution Explorer, right-click the References node and select Add Reference. On the COM tab, select “Microsoft Excel 10.0 Object Library”, and then click OK.
3.    Design a form. Add two Buttons and a Textbox.
4.    Set Name property of Button to “btnOpenExcel” and text property to “Open Excel File”.
5.    Set Name property of Button to “btnSearchExcel” and text property to “Search Excel”.
6.    Set Name property of Button to “txtSearch” and text property to “”.
7.    From Toolbox expand Dialogs group double click on the “OpenFileDialog”.
8.    In the code behind file import the library Microsoft Excel 10.0 Object Library using: using Excel;
9.    Before the Form constructor add the following code.

//Add a reference to excel.application

private Excel.Application exc;

      //Add a reference to workbooks

private Workbooks workbooks;


10.    Add class disposed event handler “Form1_Disposed”. Inside the form disposed event handler add the following code.

if (exc != null)

    exc = null;


11.    Double click on the Button “btnOpenExcel” and pest the following code into the “btnOpenExcel_Click” event.

try

{

  //Creating new excel.application

  exc = new Excel.Application();


  //Prepare open file dialog to only search for excel files

  this.openFileDialog1.FileName = "*.xls";

  if (this.openFileDialog1.ShowDialog() == DialogResult.OK)

  {

    //To get the workbooks collection

    Workbooks workbooks = exc.Workbooks;

    // Here is the call to Open a Workbook in Excel

    // It uses most of the default values                                     

    workbooks.Open(openFileDialog1.FileName, 0, true, 5,

           "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0,  

                  true, 0, 0);


    // Get opened excel file name

    label2.Text = openFileDialog1.FileName;

                    

    //To make application visible

    exc.Visible = true;                    

  }

}

catch (Exception ex)

{

  MessageBox.Show(ex.Message.ToString());

}

finally

{

  exc = null;

}


12.    Double click on the Button “btnSearchExcel” and pest the following code into the “btnSearchExcel_Click” event.

    if (exc != null)

            {

                try

                {                

                    //To get the workbook

                    _Workbook workbook =  workbooks.get_Item(1);

                    

                    //To get the worksheets collection

                    Sheets sheets = workbook.Worksheets;

                    Worksheet worksheet = (Worksheet)sheets.get_Item(1);


                    //Calling search function

                    SearchExample(worksheet, txtSearch.Text);            

                    

                }

                catch(Exception ex)

                {

                    MessageBox.Show(ex.Message.ToString());

                }  

       }


13.    Create a method “SearchExample” with parameters i.e. private void SearchExample(Excel.Worksheet ws, string sFindMe) and pest the following code inside the method.

        Excel.Range rgFound;

            string sFirstFoundAddress;


            // Set via Excel's user interface. following settings are most

        // default value

            rgFound = ws.Cells.Find(sFindMe, ws.get_Range("A1", "A1"),

            Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,

            XlSearchOrder.xlByRows, XlSearchDirection.xlNext, false,

            false, false);


            // If Find function doesn't find anything, rgFound will be null

            if (rgFound != null)

            {

                // Save the address of the first found item -

                // it will be used in a loop terminating condition.

                sFirstFoundAddress = rgFound.get_Address(

                        true, true, Excel.XlReferenceStyle.xlA1, null, null);


                MessageBox.Show("Found match at cell " + sFirstFoundAddress);


                // Continue finding subsequent items using FindNext

                rgFound = ws.Cells.FindNext(rgFound);

                string sAddress = rgFound.get_Address(

                        true, true, Excel.XlReferenceStyle.xlA1, null, null);


                // Start a loop that calls FindNext until

                // the first found cell is found again

                while (!sAddress.Equals(sFirstFoundAddress))

                {

                    MessageBox.Show("Found match at cell " + sAddress);

                    rgFound = ws.Cells.FindNext(rgFound);

                    sAddress = rgFound.get_Address(

                        true, true, Excel.XlReferenceStyle.xlA1, null, null);

                }

            }

            MessageBox.Show("The worksheet has been searched.");


Press F5 to build and run the project.

14.    Click on the Button “Open Excel File” and select an excel file using “OpenFileDialog” window and Click on the Button “Open”. Your selected Excel file will be open.
15.    Add your search text into the Textbox “txtSearch”.
16.    Click on Button “Search”. You will be prompted when search item found and also prompted when no item found.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      amater 

      7 years ago

      hi, thanks for the great code but you could have uploaded source code file/folder for download, it would be much easyer

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)