我使用以下代码打开文件:
object MissingValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Open(filepath, MissingValue, false,
MissingValue, MissingValue, MissingValue, MissingValue,MissingValue,
MissingValue, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue);
我尝试了以下所有内容来保存并关闭文件,所有这些都导致COM错误,因为文件是只读文件:
xlApp.DisplayAlerts = false;
Excel.Workbooks wbs = xlApp.Workbooks;
foreach (Excel.Workbook wb in wbs)
{
Console.WriteLine(wb.Name);
wb.Save();
wb.Close();
}
//xlWorkBook.Save();
//xlWorkBook.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
//false, false, Excel.XlSaveAsAccessMode.xlNoChange,
//Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//xlWorkBook.Close();
//xlWorkBook.Close(true, filepath, filepath);
//xlWorkBook.Close(false, MissingValue, MissingValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
我想知道可能出现什么问题,因为我引用了其他问题。请帮忙!。谢谢你的时间。
答案 0 :(得分:0)
我找到了解决方案。我使用Excel.range来更新所需的单元格值。 当我在其他人之前释放Range对象时,它成功保存并关闭。谢谢大家:) 发布代码如下:
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}