使用interop创buildexcel文件时防止打开Excel

您好所有创build一个Excel使用Microsoft Office Interop.and它创build文件成功。但问题是,当它创build一个文件,它只是打开Excel中增加了值的Excel中,并保存在指定的名称。任何意外打字时间的结果导致一个exception。创build近75个文件与数据库中的许多行,因此需要时间。在处理过程中,我不能做任何任务,因为它创buildexception,如果它的types在Excel中。是否有任何方法来运行的过程在后台,以便excel应用程序不会为每个文件创build打开。

Excel.Application oXL; Excel.Workbook oWB; Excel.Worksheet oSheet; Excel.Range oRange; // Start Excel and get Application object. oXL = new Excel.Application(); // Set some properties oXL.Visible = true; oXL.DisplayAlerts = false; // Get a new workbook. oWB = oXL.Workbooks.Add(Missing.Value); // Get the active sheet oSheet = (Excel.Worksheet)oWB.ActiveSheet; oSheet.Name = "Sales"; // Process the DataTable // BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE DataTable dt = dtt; int rowCount = 1; foreach (DataRow dr in dt.Rows) { rowCount += 1; for (int i = 1; i < dt.Columns.Count + 1; i++) { // Add the header the first time through if (rowCount == 2) { oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName; } oSheet.Cells[rowCount, i] = dr[i - 1].ToString(); } } // Resize the columns //oRange = oSheet.get_Range(oSheet.Cells[1, 1], // oSheet.Cells[rowCount, dt.Columns.Count]); oRange = oSheet.Range[oSheet.Cells[1, 1], oSheet.Cells[rowCount, dt.Columns.Count]]; oRange.EntireColumn.AutoFit(); // Save the sheet and close // oSheet = null; oRange = null; oWB.SaveAs("" + username + " .xls", Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); oWB.Close(Missing.Value, Missing.Value, Missing.Value); oWB = null; oXL.Quit(); // Clean up // NOTE: When in release mode, this does the trick GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); 

尝试这个…

//启动Excel并获取应用程序对象。 oXL = new Excel.Application { Visible = false };

  • 或者 – //设置一些属性oXL.Visible = false ;

默认情况下,通过Interop打开Excel作为Invisible。
这是你的代码改变了Excel的可见性。 删除线

 oXL.Visible = true; 

或者设置为false

 oXL.Visible = false;