简体   繁体   中英

Can't iterate over excel Sheet collection in C#

Can't iterate over excel Sheet collection in C#, , the worksheet from the Sheets collection is somehow the same worksheet every time(the first one from the Sheets).

wsheets.Count == 3

        private void frmExcel_Data_Load(object sender, EventArgs e)
        {
            //gridviews references
            DataGridView dataGridView1 = dataGrid_Excel;
            DataGridView dataGridView2 = dataGrid_Excel2;
            DataGridView dataGridView3 = dataGrid_Excel3;

            List<DataGridView> dataGridViews = new List<DataGridView>() { dataGridView1, dataGridView2, dataGridView3 };

            foreach(DataGridView dataGridView in dataGridViews)
            {
                SheetToGridView(dataGridView);
            }
        }


        private void SheetToGridView(DataGridView dataGridView)
        {
            try
            {
                //Problem
                Sheets wsheets = Globals.ThisAddIn.Application.Sheets;
                //read_Excel_File_into_DataGridView(wsheets[2], dataGridView);// Second worksheet is retrieved
                for (int i = 1; i < Globals.ThisAddIn.Application.Sheets.Count; i++)
                {
                    read_Excel_File_into_DataGridView(Globals.ThisAddIn.Application.Sheets[i], dataGridView);//Same wsheet everytime (the first one from collection)
                }
                //foreach (Worksheet wsheet in wsheets)
                //{
                //    read_Excel_File_into_DataGridView(wsheet, dataGridView);//Same wsheet everytime (the first one from collection)
                //}
            }
            catch (Exception) { }
        }

I'm speculating because I just tried this on a regular interop project, but if you access the Sheets from the workbook instead of the application object, it seems to work fine. Just as a test, I ran this to see that the name was changing, to be sure I had the correct worksheet object each time.

This may not be your issue. I mentioned in my comment it's possible your read_Excel_File_into_DataGridView method is accepting but ignoring the parameter of the worksheet you are passing.

However, try this and see if it's any better.

Microsoft.Office.Interop.Excel.Application excel = 
    (Microsoft.Office.Interop.Excel.Application)Marshal.GetActiveObject("Excel.Application");
Workbook wb = (Workbook)excel.ActiveWorkbook;

for (int i = 1; i < wb.Worksheets.Count; i++)
{
    MessageBox.Show(wb.Worksheets[i].Name);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM