C#WForm操作EXCEL

1.注册dsoframer.ocx,添加dsoframer的引用

2.在窗体中加入DSO Framer Control Object

3.声明以下变量

        private String path = AppDomain.CurrentDomain.BaseDirectory;
        Boolean bOpen = false;
        Object refmissing = System.Reflection.Missing.Value;
        private Workbook wbb;
        private Workbook wb;
        private Worksheet ws;
        private Microsoft.Office.Interop.Excel.Application oApp;

 4.打开、关闭excel

        //打开EXCEL
        public void openExcel(String filepath)
        {
            if (bOpen)
            {
                ExcelExit();
            }
            prevone = filepath;
            this.axFramerControl1.Close();
            this.axFramerControl1.Open(filepath);
            this.axFramerControl1.Activate();
            bOpen = true;
            this.axFramerControl1.Menubar = false;
            this.axFramerControl1.Titlebar = false;
            this.axFramerControl1.Toolbars = true;
            wbb = this.axFramerControl1.ActiveDocument as Workbook;
            oApp = wbb.Application as ApplicationClass;
            wb = oApp.Workbooks[oApp.Workbooks.Count];
        }
        //关闭EXCEL
        public void ExcelExit()
        {
            if (bOpen)
            {
                wbb.Save();
                this.axFramerControl1.Save();
                NAR(wbb);
                wbb.Close(false, wbb.FullName, refmissing);
                this.axFramerControl1.Close();
                oApp.Quit();
                NAR(oApp);

            }
            bOpen = false;
            ws = null;
            wb = null;
            wbb = null;
            oApp = null;
        }
        private void NAR(Object o)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
            }
            catch
            {

            }
            finally
            {
                o = null;
            }
        }

 5.关闭EXCEL最重要的两行

                                this.axFramerControl1.Close();
                                wbb.Close();

 6.选择EXCEL下一行

                Range range = ws.Rows[nowrownum] as Range;
                range.Select();

 7.给EXCEL添加改变选择行事件

            oApp.SheetSelectionChange += new AppEvents_SheetSelectionChangeEventHandler(Workbook_SheetSelectionChange);

 

你可能感兴趣的:(C#WForm操作EXCEL)