0

I'm building an app which take some data from a excel file and using them to do something else.

Well, I ask user to browse for a excel file and then I ask him in which sheet i should look for data.

Here is my code:

    using Excel = Microsoft.Office.Interop.Excel;

    string strFilePath;
    Excel.Application xlExcelApp = new Excel.Application() { };
    Excel.Workbook xlWorkBook = null;
    Excel.Worksheet xlWorkSheet = null;


    OpenFileDialog myOpenFileDialog = new OpenFileDialog();

        if (myOpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            strFilePath = myOpenFileDialog.FileName;
            txtPath.Text = strFilePath;
        }

     xlWorkBook = xlExcelApp.Workbooks.Open(strFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

        foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in xlWorkBook.Worksheets)
        {
            cmbSheetName.Items.Add(wSheet.Name.ToString());
        }

Then I have this event:

private void cmbSheetName_SelectedIndexChanged(object sender, EventArgs e)
{
     xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[cmbSheetName.SelectedIndex];

     // ...
}

Last line of code give me an error ( "Invalid index ..." ). And I don't know how to get all rows/columns from that excel file.

Can someone help me please?

Please forgive my English!

Dan
  • 139
  • 2
  • 3
  • 10
  • possible duplicate of [How do I get an Excel range using row and column numbers in VSTO / C#?](http://stackoverflow.com/questions/2333202/how-do-i-get-an-excel-range-using-row-and-column-numbers-in-vsto-c) – igorushi Feb 10 '15 at 10:50

1 Answers1

2

The indexes are 1 based, try this:

(Excel.Worksheet)xlWorkBook.Worksheets.get_Item(cmbSheetName.SelectedIndex + 1);
igorushi
  • 1,855
  • 21
  • 19