Excel 工作表不会删除 [C#、WPF、VS 2010]

本文关键字:WPF VS 2010 工作 删除 Excel | 更新日期: 2023-09-27 18:22:03

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
object misValue = System.Reflection.Missing.Value;
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Open(System.IO.Directory.GetCurrentDirectory() + @"'Report.xlsx");
// Get current worksheet and clear it
Microsoft.Office.Interop.Excel._Worksheet worksheet1 = workbook.Worksheets[1];
Microsoft.Office.Interop.Excel._Worksheet worksheet2 = workbook.Worksheets[2];
app.DisplayAlerts = false;
worksheet1.Delete();
worksheet2.Delete();
app.DisplayAlerts = true;
//app.Worksheets[1].Delete();
//app.Worksheets[2].Delete();
workbook.Save();
Microsoft.Office.Interop.Excel._Worksheet worksheet = (Excel.Worksheet)app.Worksheets.Add(); ;
// storing header part in Excel
for (int i = 1; i < mydatatable.Columns.Count + 1; i++)
{
    worksheet.Cells[1, i] = mydatatable.Columns[i - 1].ColumnName.ToString();
}
// storing Each row and column value to excel sheet
for (int i = 0; i < mydatatable.Rows.Count; i++)
{
    for (int j = 0; j < mydatatable.Columns.Count; j++)
    {
        worksheet.Cells[i + 2, j + 1] = mydatatable.Rows[i][j].ToString();
    }
    worksheet.Columns.AutoFit();
}
Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)worksheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = worksheet.get_Range("C1", "E20");
chartPage.SetSourceData(chartRange);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered;
chartPage.Location(Excel.XlChartLocation.xlLocationAsNewSheet,"Chart");
workbook.Save();
workbook.Close(misValue);
Marshal.ReleaseComObject(worksheet);
app.Quit();

它完美地创建新工作表,但不会先删除旧工作表。我什至有两个代码可以删除它,但它没有。我在应用程序中有不止一张纸。

编辑:我刚刚注意到我第一次运行代码时它会删除给定的工作表,但是如果我第二次运行它(等(,它不会再删除它们并给我错误,因为出于某种原因,父级 EXCEL 进程仍然在后台打开,尽管我使用"app。退出(("。请帮忙!

Excel 工作表不会删除 [C#、WPF、VS 2010]

其中一个

问题可能是您在尝试删除工作表时有一个工作表。 确保您没有删除最后一个工作表,否则它将不起作用。 因此,创建一个新的,然后删除旧的;反之则不然。

编辑:

试试这个代码:

app.DisplayAlerts = false;
worksheetdel.Delete();
app.DisplayAlerts = true;

来源: https://stackoverflow.com/a/678795/2006048