windows 如何从 C# 中的 Excel 工作簿中删除工作表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7402169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:03:28  来源:igfitidea点击:

How to delete worksheets from Excel workbook in C#?

c#windowsexcelworksheet

提问by Tripati Subudhi

Let's say I have one workbook which is having 6 sheets as Sheet1, Sheet2, Sheet3, Sheet4, Sheet5, Sheet6.

假设我有一个工作簿,其中有 6 张工作表,如 Sheet1、Sheet2、Sheet3、Sheet4、Sheet5、Sheet6。

So from here I want to delete Sheet1, Sheet2, Sheet3. How can I do that?

所以从这里我想删除 Sheet1、Sheet2、Sheet3。我怎样才能做到这一点?

回答by VMAtm

You can call the .Delete() method, like that:

您可以调用.Delete() 方法,如下所示:

Globals.Sheet1.Delete();

Update, according your comment:

更新,根据您的评论:

Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
ws.Delete();

回答by ranga nathan

I hope this code will help you:

我希望这段代码能帮助你:

app.DisplayAlerts = false; 
worksheet.Delete(); 
app.Displayalerts = true;

where appis your XlsApplication.

其中app是您的 XlsApplication。

回答by ranga nathan

Dim s1 as Excel.Worksheet
s1 = wb.Sheets("Sheet1")
s1.Visible = Excel.XlSheetVisibility.xlSheetVisible
s1.Delete()

You need to change visibility because you can't delete a sheet with the visibility set to Excel.XlSheetVisibility.xlSheetVeryHidden

您需要更改可见性,因为您无法删除可见性设置为 Excel.XlSheetVisibility.xlSheetVeryHidden 的工作表

回答by Francesco Baruchelli

Referring to your example (How to merge two excel workbook into one workbook in c#?), where appis your variable of type Excel.Application, you should write something like this:

参考您的示例(如何在 c# 中将两个 excel 工作簿合并为一个工作簿?),其中appExcel.Application类型的变量,您应该编写如下内容:

for (int i = 1; i <= 3; i++)
    ((Excel.Worksheet)app.ActiveWorkbook.Sheets[1]).Delete();

P.S: it seems to me that the Worksheets collection is indexed starting from 1, not 0, but I'm not sure and can't check right now. If it doesn't work try with values for i from 0 to 2.

PS:在我看来,工作表集合的索引从 1 开始,而不是 0,但我不确定,现在无法检查。如果它不起作用,请尝试使用从 0 到 2 的 i 值。

回答by Davide Piras

MSDN knows:

MSDN 知道:

((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[4]).Delete();

or

或者

Globals.Sheet1.Delete();

See here: How to: Delete Worksheets from Workbooks

请参见此处:如何:从工作簿中删除工作表