Kar*_*hik 2 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();
Run Code Online (Sandbox Code Playgroud)
默认情况下,Excel通过Interop打开为Invisible.
这是改变Excel可见性的代码.删除该行
oXL.Visible = true;
Run Code Online (Sandbox Code Playgroud)
或设为false
oXL.Visible = false;
Run Code Online (Sandbox Code Playgroud)