簡體   English   中英

使用互操作創建Excel文件時阻止Excel打開

[英]Prevent Excel from opening while creating excel file using interop

大家好我正在使用Microsoft office interop創建一個excel。它成功創建文件。但問題是,當它創建一個文件時,它只是打開excel將值添加到excel並將其保存在指定的名稱。任何意外的輸入時間結果導致異常。從數據庫創建了近75個文件,並且因此需要時間。在處理過程中我無法執行任何任務,因為如果在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();

默認情況下,Excel通過Interop打開為Invisible。
這是改變Excel可見性的代碼。 刪除該行

oXL.Visible = true;

或設為false

oXL.Visible = false;

嘗試這個...

//啟動Excel並獲取Application對象。 oXL = new Excel.Application { Visible = false };

  • OR - //設置一些屬性oXL.Visible = false ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM