我编写了以下代码来从 Excel 工作簿中删除 Excel 工作表。该代码没有引发任何错误,但在打开 Excel 时,工作表不会被删除。
public void EXcelCleanup(string Excelpath)
{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.DisplayAlerts = false;
string WorkbookLocation = Excelpath;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(WorkbookLocation,
0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Microsoft.Office.Interop.Excel.Sheets worksheets = excelWorkbook.Worksheets;
int wsCount = worksheets.Count;
if (wsCount > 1)
{
for (int i = 2; i <wsCount-1; i++)
{
worksheets[i].Delete();
}
}
excelWorkbook.Save();
excelWorkbook.Close();
Marshal.ReleaseComObject(worksheets);
excelApp.Quit();
}