Microsoft.Office.Interop.Excel API 应用(一)ExcelApplication

来源:互联网 发布:lightgallery.js 编辑:程序博客网 时间:2024/05/16 16:10

1. 项目中添加引用“Microsoft.Office.Interop.Excel” ;

2. 添加using “”using Microsoft.Office.Interop.Excel;

 

Code:

using System.Threading;using System.Runtime.InteropServices;using System.Diagnostics;using System;using Microsoft.Office.Interop.Excel;namespace OfficeUtility{    /// <summary>    /// Start an excel process with some parameters setting    /// </summary>    public class ExcelApp : IDisposable    {        [DllImport("user32.dll")]        static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);        private Application excelAppInstance = null;        public Application ExcelAppInstance        {            get            {                return excelAppInstance;            }        }        /// <summary>        /// Create an new excel app instance        /// </summary>        /// <param name="visible">true if excel object is visible; otherwise visible.</param>        public ExcelApp(bool visible)        {            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");            excelAppInstance = new Microsoft.Office.Interop.Excel.Application();            excelAppInstance.Visible = visible;        }        /// <summary>        /// Create an new excel app instance        /// </summary>        /// <param name="visible">true if excel object is visible; otherwise visible.</param>        /// <param name="displayAlerts">true if  permit excel app displays certain alerts and messages while a macro is running; otherwise false.</param>        public ExcelApp(bool visible, bool displayAlerts)        {            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");            excelAppInstance = new Microsoft.Office.Interop.Excel.Application();            excelAppInstance.Visible = visible;            excelAppInstance.DisplayAlerts = displayAlerts;        }        #region IDisposable Members        /// <summary>        /// Kill the excel process        /// </summary>        public void Dispose()        {            if (excelAppInstance != null)            {                int processId;                //Call windows API get processId of the current excel app                GetWindowThreadProcessId(excelAppInstance.Hwnd, out processId);                excelAppInstance.Quit();                Thread.Sleep(5000);                Process p = Process.GetProcessById(processId);                if (p != null)                {                    try { p.Kill(); }                    catch (Exception) { }                }            }        }        #endregion    }}