2012-06-12 77 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;