简体   繁体   中英

How do I delete Excel file from Visual Studio?

VS and Excel Noob. When I use an Excel file in my Visual Studio, the file refuses to get deleted even after I stop running the code and even close Visual Studio.

I've tried to delete the file, stop code and then delete the file, closed Visual Studio. I haven't rebooted yet but I don't want to have to do that.

        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;
                    }
                }
            }
        }

I wish I could do screenshots here.

It just asks to "Try Again" to delete but it doesn't delete.

How about this code:

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);
}

In order to make it so your excel document isn't stuck open and returning the error about "file in use by another process", you need to close it in your code.

Try closing your work book and then application. This should release your excel document. Add the following to the end of your method: oWB.Close(0); then oXL.Quit();

Your code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM