C# 根据输入的保存文件路径判断Excel是否存在,存在就删除该文件

C#根据输入的保存文件路径判断Excel是否存在,存在就删除该文件

   		/// 
        /// 
        /// 根据输入的保存文件路径判断Excel是否存在,存在就删除该文件
        /// 
        /// 
        public void CheckExcel(string filePath)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Sheets sheets;
            Microsoft.Office.Interop.Excel.Workbook workbook = null;
            object oMissiong = System.Reflection.Missing.Value;
            try
            {
                workbook = app.Workbooks.Open(filePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
                sheets = workbook.Worksheets;
                app.DisplayAlerts = false;
                //app.Visible = true;//是否显示
                int sheetCount = workbook.Worksheets.Count;//sheet数量
                for (int i = 1; i <= sheetCount; i++)
                {
                    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(i);//读取表
                    worksheet.Activate();//激活sheet表
                    if (worksheet == null)
                        return;
                    Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)worksheet.Rows[1, oMissiong];
                    range.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlDown);

                    workbook.Save();
                }
                workbook.Close();
                app.Workbooks.Close();
                app.Quit();
                GC.Collect();
            }
            catch (Exception ex)
            {
                return;
            }
            //finally
            //{
            //    System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("wps");//根据进程名获取进程
            //    foreach (System.Diagnostics.Process p in process)
            //    {
            //        p.Kill();//结束进程
            //    }
            //}
        }

你可能感兴趣的:(c#,excel,开发语言,后端)