[英]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).无法在 C# 中迭代 excel Sheet 集合,Sheets 集合中的工作表每次都是同一个工作表(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.我在评论中提到,您的
read_Excel_File_into_DataGridView
方法可能正在接受但忽略了您正在传递的工作表的参数。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.