Excel c#Excel工作进程的创建写 与Excel文件的保存[原创] (20100205 11:09)

Excel工作进程的创建写结束

创建:

     Microsoft.Office.Interop.Excel.ApplicationClass oExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
           Microsoft.Office.Interop.Excel.Workbook obook = null;
           Microsoft.Office.Interop.Excel.Worksheet oSheet = null;
           Microsoft.Office.Interop.Excel.Range range = null;

结束:

方法一:用托管方法

 System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
               System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
               System.Runtime.InteropServices.Marshal.ReleaseComObject(obook);

               oExcel.Quit();
               System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);

               GC.Collect();

方法二:

 excelApp.Workbooks.Close();
                    oExcel.Quit();
                    int generation = System.GC.GetGeneration(oExcel);
                    System.GC.Collect(generation);

方法三:

   /// <summary>
        /// 销毁进程
        /// </summary>
        /// <param name="datetime">销毁进程的时间</param>
        /// <returns></returns>
        private bool KillExcelProcess(DateTime datetime)
        {
            try
            {
                System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
                for (int m = 0; m < excelProc.Length; m++)
                {
                    if (datetime < excelProc[m].StartTime)
                    {
                        excelProc[m].Kill();
                    }

                }
                return true;
            }
            catch (Exception ex)
            {
                strError = "销毁进程出错:" + ex.Message;
                return false ;
            }
        }

 

保存并替换原来单页Excel文件

 Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                excelApp.DisplayAlerts = true;
                excelApp.SheetsInNewWorkbook = 1;
                Workbook excelBook = excelApp.Workbooks.Add(Type.Missing );
                Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelBook.ActiveSheet;

 excelBook.Saved = true;
                excelBook.SaveCopyAs(strExcelFileName);

原文地址:https://www.cnblogs.com/heling/p/1664401.html