簡體   English   中英

如何從 Visual Studio 中刪除 Excel 文件?

[英]How do I delete Excel file from Visual Studio?

VS 和 Excel 菜鳥。 當我在 Visual Studio 中使用 Excel 文件時,即使我停止運行代碼甚至關閉 Visual Studio,該文件也拒絕被刪除。

我試圖刪除文件,停止代碼,然后刪除文件,關閉 Visual Studio。 我還沒有重新啟動,但我不想這樣做。

        Excel.Application oXL = new Excel.Application();

        Excel.Workbook oWB = oXL.Workbooks.Open(xlsmfilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

        Excel.Worksheet oWS = oWB.Worksheets[1] as Excel.Worksheet;

        Excel.Range range;

        range = oWS.UsedRange;

        //read first row, first cell value 
        int rowCount = range.Rows.Count;
        int colCount = range.Columns.Count;
        string roadName = string.Empty;
        //iterate over the rows and columns and print to the console as it appears in the file
        //excel is not zero based!!
        for (int i = 2; i <= rowCount; i++)
        {
            for (int j = 1; j <= colCount; j++)
            {
                if (j == 17)
                {
                    if (range.Cells[i, j].Value2 == null || range.Cells[i, j].Value2.ToString() == "")
                        break;
                    //write the value to the console
                    if (i > 1 && range.Cells[i, j] != null && range.Cells[i, j].Value2 != null && range.Cells[i, j].Value2 != "" && range.Cells[i, j].Value2.Contains(fileName))
                    {
                        roadName=range.Cells[i, 4].Value2.ToString();
                        break;
                    }
                }
            }
        }

我希望我可以在這里做截圖。

它只是要求“再試一次”刪除,但它不會刪除。

這段代碼怎么樣:

string authorsFile = "file.xlsx";

try
{
    if (File.Exists(Path.Combine(rootFolder, authorsFile)))
    {
        File.Delete(Path.Combine(rootFolder, authorsFile));
    }
    //nothing   
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

為了使您的 excel 文檔不會卡在打開狀態並返回有關“另一個進程正在使用文件”的錯誤,您需要在代碼中關閉它。

嘗試關閉您的工作簿,然后申請。 這應該會釋放您的 Excel 文檔。 將以下內容添加到您的方法末尾: oWB.Close(0); 然后oXL.Quit();

您的代碼:

Excel.Application oXL = new Excel.Application();
Excel.Workbook oWB = oXL.Workbooks.Open(xlsmfilePath, ... Missing Values ...);
...
// Code for altering workbook
... 
oWB.Close(0);
oXL.Quit();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM