Closing an Excel Workbook

前端 未结 5 782
無奈伤痛
無奈伤痛 2021-01-13 00:34

I have a bit of code that opens an xls workbook;

Excel.Workbooks workBooks;
workBooks = excelApp.Workbooks;
workbook = workBooks.Open(sourceFilePath + source         


        
5条回答
  •  甜味超标
    2021-01-13 01:04

    Here is the solution

    first: using EXCEL = Microsoft.Office.Interop.Excel;

    and then, path is where your excel locates.

            EXCEL.Application excel = new EXCEL.Application();
            try
            {
                EXCEL.Workbook book = excel.Application.Workbooks.Open(path);
                EXCEL.Worksheet sheet = book.Worksheets[1];
                // yout operation
    
            }
            catch (Exception ex) { MessageBox.Show("readExcel:" + ex.Message); }
            finally
            {
                KillExcel(excel);
                System.Threading.Thread.Sleep(100);
            }
    
    
    
        [DllImport("User32.dll")]
        public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);
        private static void KillExcel(EXCEL.Application theApp)
        {
            int id = 0;
            IntPtr intptr = new IntPtr(theApp.Hwnd);
            System.Diagnostics.Process p = null;
            try
            {
                GetWindowThreadProcessId(intptr, out id);
                p = System.Diagnostics.Process.GetProcessById(id);
                if (p != null)
                {
                    p.Kill();
                    p.Dispose();
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("KillExcel:" + ex.Message);
            }
        }
    

提交回复
热议问题