如何在C#中处理excel工作表的另存为对话框

时间:2017-06-20 11:03:49

标签: c# .net excel interop

我正在尝试在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表中输入值但不保存它。有人可以帮忙缩短这个问题吗?或建议更好的方法?

1 个答案:

答案 0 :(得分:1)

尝试手动将$passedValidation属性设置为Saved

true

修改

您可以向the Close() method提供参数。在C#中,我相信这将是这样的:

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