C#生成的工作表是只读和locking的

我有一个打开和保存我的C#程序生成的Excel文件的问题。 每次手动进行一些更改并尝试保存excel文件时,popup消息会要求我保存该文件的副本,因为它是只读的。 这是好的,但烦人的。 我的excel文件是由我的C#程序生成的。 这是我的代码片段:

/** * Save the matched data * */ public void saveMatch(List<String> saveB, List<String> saveG, Excel.Worksheet bellSheet, Excel.Worksheet GSMSheet, String fileurl, String mCode, String prioName,int sNumber = 0) { object misValue = System.Reflection.Missing.Value; Excel.Application newApp = new Excel.Application(); Excel.Workbook newWB = newApp.Workbooks.Add(misValue); Excel.Worksheet newWS = newWB.Worksheets.get_Item(1); String colName1 = bSheet.get_Range("A1").Cells.Value; String colName2 = GSheet.get_Range("A1").Cells.Value; int i = 2;//start copy from row two of the Sheet, row one is the column name newWS.Cells[1, 2] = colName2;//copy the column name newWS.Cells[1, 1] = colName1;//copy the column name //Copy excatly matching data for (int j = 0; j < saveB.Count; j++) { newWS.Cells[i, 1] = saveB[j]; newWS.Cells[i, 2] = saveG[j]; //Console.WriteLine(saveG[j] + " : " + saveB[j]); i++; } if (sNumber==0) { if (prioName.Equals("None")) { newWB.SaveAs(fileurl + @"\MdResults_" +"None_"+ mCode + ".xlsx"); } else { newWB.SaveAs(fileurl + @"\MdResults_" + prioName+"_"+mCode + ".xlsx"); } } else { if (prioName.Equals("None")) { newWB.SaveAs(fileurl + @"\MdResults_" + "None_"+mCode + "_" + sNumber + ".xlsx"); } else { newWB.SaveAs(fileurl + @"\MdResults_" +prioName + "_"+mCode + "_" +sNumber + ".xlsx"); } } newWB.Close(0); newApp.Quit(); 

程序运行正常,我可以成功打开保存的Excel文件。 我只是想知道我在C#代码中丢失了什么,或者我只需要修改Excel文件本身中的某些内容? 我希望我的程序生成的excel文件可以修改并保存为正常,而不popup消息要求我保存为副本。 谢谢您的帮助。

如果您不closuresnewApp,则Excel进程将在内存中保留并locking您的文件。

检查您的任务列表,以确认这是发生。

在保存文件后尝试添加以下内容

 newApp.Close(0); newApp.Quit();