使用互操作创建Excel文件时阻止Excel打开

时间:2012-06-12 07:25:28

标签: c# excel office-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();

2 个答案:

答案 0 :(得分:5)

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

oXL.Visible = true;

或设为false

oXL.Visible = false;

答案 1 :(得分:4)

试试这个......

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

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