公共变量的引用迷失在c#中

时间:2012-04-02 03:00:58

标签: c# .net excel interop

我正在课堂上宣布

public Excel.Range range { get; set; } 

该类的构造函数调用此方法:

private void OpenWorkBook()
        {
            string str;
            int rCnt = 0;
            int cCnt = 0;


            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open(MasterFileName, 0, true, 5, "", "", true,
                Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
                "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;  
        }

之后我从另一种方法引用range

public void CreateFiles(string column)
        {
            try
            {
                var valueRange = range.get_Range(column + "3", column + range.Rows.Count.ToString());
                var deleteRange = range;

我得到了:

valueRange threw an exception of type System.Runtime.InteropServices.InvalidComObjectException'

有谁知道为什么我要丢失这个变量的内容?

这是我的完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;

namespace EmailSalesVolumeSolution
{
    class WorkBook
    {
        public string MasterFileName { get; set; }
        public string[] DistinctEmails { get; set; }
        public Excel.Application xlApp {get;set;}
        public Excel.Workbook xlWorkBook { get; set; }
        public Excel.Worksheet xlWorkSheet { get; set; }
        public Excel.Range range { get; set; }        

        private void OpenWorkBook()
        {
            string str;
            int rCnt = 0;
            int cCnt = 0;


            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open(MasterFileName, 0, true, 5, "", "", true,
                Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
                "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;  
        }

        public WorkBook(string filename)
        {
            MasterFileName = filename;
            //xlWorkBook = null;
            //xlApp = null;
            //xlWorkSheet = null;
            //range = null;

            OpenWorkBook();
        }


        public void SendEmail()
        {

        }
        public void CreateFiles(string column)
        {
            try
            {
                var valueRange = range.get_Range(column + "3", column + range.Rows.Count.ToString());
                var deleteRange = range;
                string cell = "";

                DistinctEmails = DistinctValues(valueRange);

                foreach (string email in DistinctEmails)
                {
                    for (int rCnt = 2; rCnt <= valueRange.Rows.Count; rCnt++)
                    {
                        cell = (string)(valueRange.Cells[rCnt, 1] as Excel.Range).Value2;
                        if (cell == null || cell != email)
                        {
                            deleteRange=xlWorkSheet.get_Range(column + rCnt.ToString() + ":" + column + rCnt.ToString(), Type.Missing);
                            deleteRange.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
                        }
                    }
                    xlWorkBook.SaveAs(xlWorkBook.Path + @"\" + email, Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
                    false, false, Excel.XlSaveAsAccessMode.xlNoChange,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                //DisposeMe();
                // Release all COM RCWs.
                // The "releaseObject" will just "do nothing" if null is passed,
                // so no need to check to find out which need to be released.
                // The "finally" is run in all cases, even if there was an exception
                // in the "try". 
                // Note: passing "by ref" so afterwords "xlWorkSheet" will
                // evaluate to null. See "releaseObject".
                releaseObject( xlWorkSheet);
                releaseObject( xlWorkBook);
                // The Quit is done in the finally because we always
                // want to quit. It is no different than releasing RCWs.
                if (xlApp != null)
                {
                    xlApp.Quit();
                }
                releaseObject( xlApp);
            }
        }

        private string[] DistinctValues(Excel.Range EmailList)
        {
            string cell = "";
            List<string> emails = new List<string>();            

            for (int rCnt = 1; rCnt <= EmailList.Rows.Count; rCnt++)
            {
                cell = (string)(EmailList.Cells[ rCnt,1] as Excel.Range).Value2;
                if (cell!=null)
                    emails.Add(cell.ToString());
            }

            releaseObject(EmailList);

             return emails.Distinct().ToArray();
        }
        private void releaseObject( object obj) // note ref!
        {
            // Do not catch an exception from this.
            // You may want to remove these guards depending on
            // what you think the semantics should be.
            if (obj != null && Marshal.IsComObject(obj))
            {
                Marshal.ReleaseComObject(obj);
            }
            // Since passed "by ref" this assingment will be useful
            // (It was not useful in the original, and neither was the
            //  GC.Collect.)
            obj = null;
        }


        private void DisposeMe()
        {

            // Cleanup:
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Marshal.FinalReleaseComObject(xlWorkSheet);

            xlWorkBook.Close(false, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(xlWorkBook);

            xlApp.Quit();
            Marshal.FinalReleaseComObject(xlApp);
        }
    }
}

这是我如何实例化类!!

private void button1_Click(object sender, EventArgs e)
        {

            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
            if (result == DialogResult.OK) // Test result.            
                InitializeWorkBook(openFileDialog1.FileName);




        }
        private void InitializeWorkBook(string filename)
        {
            WorkBook wb= new WorkBook(filename);
            wb.CreateFiles("A");

        }

0 个答案:

没有答案