C#强制关闭Excel进程(通过COM使用Excel时)
1 //ExcelInstances
2 using System;
3
4 public class Class1
5 {
6 public Class1()
7 {
8 }
9 }
10 public class ExcelInstances{
11 private static Microsoft.Office.Interop.Excel.Application m_excelApp = null;
12 private static Microsoft.Office.Interop.Excel.Workbooks m_excelWorkBooks = null;
13 [DllImport("User32.dll")]
14 public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int Processid);
15 private ExcelInstances()
16 {
17 }
18
19 // 初?始n化âExcelInstances后@,C生÷成Ê相?应的ICOM实例a
20 private static void Init()
21 {
22 if (m_excelApp == null)
23 {
24 m_excelApp = new Microsoft.Office.Interop.Excel.Application();
25 m_excelApp.DisplayAlerts = false;
26 m_excelApp.AlertBeforeOverwriting = false;
27 }
28 if (m_excelWorkBooks == null)
29 {
30 if (m_excelApp != null)
31 {
32 m_excelWorkBooks = m_excelApp.Workbooks;
33 }
34 }
35 }
36
37 // 辅助?功€能¬获取a当?前O系n统中?Excel的I进程o数?
38 public static int GetExcelProcessCount()
39 {
40 int iReturn = 0;
41 System.Diagnostics.Process[] pProcesses = null;
42 try
43 {
44 pProcesses = System.Diagnostics.Process.GetProcesses();
45 foreach (System.Diagnostics.Process p in pProcesses)
46 {
47 if (string.Equals(p.ProcessName.ToString(), "EXCEL"))
48 {
49 iReturn++;
50 }
51 }
52 }
53 catch (Exception e)
54 {
55 throw e;
56 }
57 return iReturn;
58 }
59 // 强行s关闭指w定e的IExcel进程o
60 public static void Kill(Microsoft.Office.Interop.Excel.Application theApp)
61 {
62 int iId = 0;
63 IntPtr intptr = new IntPtr(theApp.Hwnd);
64 System.Diagnostics.Process p = null;
65 try
66 {
67 GetWindowThreadProcessId(intptr, out iId);
68 p = System.Diagnostics.Process.GetProcessById(iId);
69 if (p != null)
70 {
71 p.Kill();
72 p.Dispose();
73 }
74 }
75 catch (Exception e)
76 {
77 throw e;
78 }
79 }
80 private static ExcelInstances _objInstances = null;
81 // 获得?一e个‘ExcelInstances 的I实例a
82 public static ExcelInstances GetInstances()
83 {
84 if (_objInstances == null)
85 {
86 _objInstances = new ExcelInstances();
87 }
88 Init();
89 return _objInstances;
90 }
91 // 按A照A文÷件?名?获得?指w定e的Iworkbook
92 public Microsoft.Office.Interop.Excel.Workbook GetWorkBook(string strFileName)
93 {
94 return m_excelWorkBooks.Add(strFileName);
95 }
96 // 关闭workbook
97 public void Close()
98 {
99 try
100 {
101 if (m_excelWorkBooks != null)
102 {
103 m_excelWorkBooks.Close();
104 System.Runtime.InteropServices.Marshal.ReleaseComObject(m_excelWorkBooks);
105 m_excelWorkBooks = null;
106 }
107 if (m_excelApp != null)
108 {
109 m_excelApp.Quit();
110 System.Runtime.InteropServices.Marshal.ReleaseComObject(m_excelApp);
111 m_excelApp = null;
112 }
113 }
114 catch (Exception e)
115 {
116 throw e;
117 }
118 }
119 }
posted on 2011-04-16 18:34 Osiris4Net 阅读(802) 评论(0) 编辑 收藏 举报