2012-06-12 44 views
2

大家好,我正在使用Microsoft Office Interop创建excel,并且它成功创建了文件。但问题是,创建文件时它只是打开excel将值添加到excel中并将其保存在指定的名称中。当时任何意外键入都会导致异常。从数据库创建近75个包含多行的文件,因此需要时间。在处理期间,我无法执行任何任务,因为它会在创建异常时在excel中键入。是否有任何方法在后台运行进程,以便excel应用程序不会为每个文件创建打开。在使用互操作创建excel文件时防止Excel打开

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(); 

回答

4

尝试......

//启动Excel并得到应用对象。 oXL = new Excel.Application {Visible = false};

  • OR - //设置一些属性oXL.Visible = ;
5

默认情况下,Excel通过Interop打开为不可见。
这是您的代码,它改变了Excel的可见性。 卸下线

oXL.Visible = true; 

或设置为false

oXL.Visible = false;