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;
}
}
}
}
我希望我可以在这里做截图。
它只是要求“再试一次”删除,但它不会删除。
为了使您的 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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句