简体   繁体   English

如何确定 Excel 工作簿中有多少个工作表?

[英]How can I determine how many worksheets there are in an Excel workbook?

thanks in advance for your help.在此先感谢您的帮助。 I want to loop through all worksheets in a workbook.我想遍历工作簿中的所有工作表。 Unfortunately, I don't know how many worksheets there are in a given workbook.不幸的是,我不知道给定工作簿中有多少工作表。 Right now I use the following technique to enumerate through all worksheets:现在我使用以下技术来枚举所有工作表:

Excel.Worksheet xlWorkSheet1;
xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Worksheet xlWorkSheet2;
xlWorkSheet2 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
Excel.Worksheet xlWorkSheet3;
xlWorkSheet3 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);

Is there a method that returns the number of worksheets in a workbook?有没有一种方法可以返回工作簿中工作表的数量?

使用Excel.Workbook ,然后您可以在forwhile循环中使用Workbook.Sheets.Count()

Googling this results in either this page, or several others where you have to use VBA or C# or start mucking about in the Name Manager in Excel. 谷歌搜索这会导致此页面或其他几个您必须使用VBA或C#或在Excel中的名称管理器中开始乱码。

Anyone looking for a quick and dirty solution: 任何寻找快速和肮脏的解决方案的人:

Open the xlsx file with 7zip and navigate to xl\\worksheets. 使用7zip打开xlsx文件并导航到xl \\ worksheets。 In there you should see all the sheets, and if you select those 7zip will count them for you. 在那里你应该看到所有的纸张,如果你选择那些7zip会为你计算它们。

Insert a module in the workbook you want to count the total sheets of, Then type the below code and hit run 在工作簿中插入要计算总表数的模块,然后键入以下代码并点击运行

Public Sub CountWorksheets()
       MsgBox "Total Sheets count:" & Application.Sheets.Count

End Sub

You'll get a relevant output like below 您将获得如下所示的相关输出

产量

The Worksheets property has a collection of the worksheets . Worksheets属性包含工作表的集合。

foreach (Excel.Worksheet xlworksheet in xlworkbook.Worksheets)
{
    //xlworksheet code here
}

Or, get the count value and use a for loop. 或者,获取计数值并使用for循环。

我们现在可以使用: int Workbook.Sheets.Count

I use such code我用这样的代码


//Create application.
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();

//Opening excel book
Workbook ObjWorkBook = ObjExcel.Workbooks.Open(excelFileLocation, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);

//Getting sheets count
int sheetsCount = ObjWorkBook.Worksheets.Count;

For this code to work, you need to install the package using NuGet - Microsoft.Office.Interop.Excel要使此代码正常工作,您需要使用 NuGet - Microsoft.Office.Interop.Excel 安装程序包

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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