我试图在excel工作表中写几行,然后使用简单的c#程序保存。但是每次它显示带有“您要保存此文件?”的对话框时。是,否,取消选项。我想选择“是”,以便可以将文件与更新的数据一起保存。

这是代码:

string ID = "123456";

Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open(@"D:\Projects\Data\DataSheet.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet =
(Microsoft.Office.Interop.Excel.Worksheet) xlWorkBook.Worksheets["source"];
//putting the value in excel.
xlWorkSheet.Cells[2, 2] = ID;

xlApp.Visible = true;
//xlApp.ActiveWorkbook.save();

xlWorkBook.SaveAs(@"D:\Projects\Data\DataSheet.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

xlWorkBook.Close(false, Type.Missing, Type.Missing);
xlApp.Workbooks.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);

xlApp.Quit();
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);


它在excel工作表中输入值,但不保存。有人可以帮助缩短这个问题吗?或提出更好的方法?

最佳答案

尝试将Saved属性手动设置为true

xlWorkBook.SaveAs(...);
xlWorkBook.Saved = true;
xlApp.Workbooks.Close()  //not sure if required before: xlWorkBook.Close()




编辑

您可以为the Close() method提供参数。在C#中,我相信这看起来像这样:

xlWorkBook.SaveAs(...);
xlWorkBook.Saved = true;
xlWorkBook.Close(false); //new line
xlApp.Workbooks.Close(); OR xlApp.Workbooks.Close(false);

10-04 13:21