How to delete worksheets from Excel workbook in C#?
Let's 开发者_开发技巧say I have one workbook which is having 6 sheets as Sheet1, Sheet2, Sheet3, Sheet4, Sheet5, Sheet6.
So from here I want to delete Sheet1, Sheet2, Sheet3. How can I do that?
You can call the .Delete() method, like that:
Globals.Sheet1.Delete();
Update, according your comment:
Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
ws.Delete();
I hope this code will help you:
app.DisplayAlerts = false;
worksheet.Delete();
app.Displayalerts = true;
where app is your XlsApplication.
MSDN knows:
((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[4]).Delete();
or
Globals.Sheet1.Delete();
See here: How to: Delete Worksheets from Workbooks
Referring to your example (How to merge two excel workbook into one workbook in c#?), where app is your variable of type Excel.Application, you should write something like this:
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.
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
精彩评论