1、不弹出excel保存提示框
2、在后台打开excel
System.Reflection.Missing misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
//设置禁止弹出保存和覆盖的询问提示框
xlApp.DisplayAlerts = false;
xlApp.AlertBeforeOverwriting = false;
//让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写
xlApp.Visible = false;
//新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错
Workbooks workbooks = xlApp.Workbooks;
Workbook workbook = workbooks.Add(true);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
// 用反射获取类型的所有属性(以便后续生成所有Column的标题)
Type type = typeof(DurationTimeInfo);
object obj = Activator.CreateInstance(type);
PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
try
{
for (int i = 0; i < props.Length; i++)
{
worksheet.Cells[1, i + 1] = props[i].Name; //write the column name
}
for (int i = 0; i < durationTimeInfoList.Count; i++)
{
worksheet.Cells[i + 2, 1] = durationTimeInfoList[i].InstrumentId;
worksheet.Cells[i + 2, 2] = durationTimeInfoList[i].ValidBeginTime;
worksheet.Cells[i + 2, 3] = durationTimeInfoList[i].ValidEndTime;
worksheet.Cells[i + 2, 4] = durationTimeInfoList[i].ValidSeconds;
worksheet.Cells[i + 2, 5] = durationTimeInfoList[i].TotalValidSeconds;
}
workbook.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(Type.Missing, Type.Missing, Type.Missing);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
//确保Excel进程关闭
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}