保存已创建的Excel文件后,无法断开与Excel Introp的连接

我试图保存一个使用Excel Interop通过C#应用程序创建和写入的Excel文件。 我已经遍寻这个网站作为其他人找到一个适当的代码,我还没有找到一个。 我的excel interop funciton使用工作簿,工作表,应用程序和workshee_range对象。 有没有人有什么建议。 解决方案越容易越好。 我是初级到中级C#程序员,高级解决方案可能超出我的知识范围。 在保存并关闭excel文件后,尝试断开与excel interop的连接时出现未处理的异常,说'未将对象引用设置为对象的实例'。

这里是我用来完成上述过程的代码:

            workbook.SaveAs(startForm.excelFileLocation);
            workbook.Close();
            app.Quit();
            Marshal.ReleaseComObject(workSheet_range);
            Marshal.ReleaseComObject(worksheet);
            Marshal.ReleaseComObject(workbook);
            Marshal.ReleaseComObject(app);
            app = null;
            workbook = null;
            worksheet = null;
            workSheet_range = null;

以下是完整的代码:

     class CreateExcelDoc
    {
        string newFormString = trialReportForm.newFormString;
       string fileString=trialReportForm.fileString;
       int sheetCount;
       string trialString = trialReportForm.trialString;
       string dateString = trialReportForm.dateString;
       string saveString = trialReportForm.saveSting;
       System.Windows.Forms.Timer excelTimer = new System.Windows.Forms.Timer();
        private Excel.Application app = null;
        private Excel.Workbook workbook = null;
        private Excel.Worksheet worksheet = null;
        private Excel.Range workSheet_range = null;
        public CreateExcelDoc()

        {
            createDoc();
        }

        public void createDoc()
        {

            try
            {
                app = new Excel.Application();
                //app.Visible = false;
                if (startForm.exportOwnerString == "Yes")
                {
                    app.Visible = true;
                    startForm.exportOwnerString = " ";
                }
                else
                {
                    app.Visible = false;
                }
                if (startForm.excelActionFlag=="addNewTrialReport")
                {
                    workbook = (Excel.Workbook) app.Workbooks.Add(1);
                    //workbook.SaveAs(newFileForm.desktopPath + "" + "OB "+trialReportForm.otrClubNameString+" - "+trialReportForm.otrDateString);
                    worksheet = (Excel.Worksheet)workbook.Worksheets[1];
                    //fileNameString = newFileForm.desktopPath + "OB " + trialReportForm.otrClubNameString + " " + trialReportForm.otrDateString;
                    workbook.Worksheets[1].Name = trialReportForm.trialReportDate+" Trial "+trialReportForm.trialReportTrialNumber;
                }
                else if (startForm.excelActionFlag == "ownerContacts")
                {
                    workbook = (Excel.Workbook)app.Workbooks.Add(1);
                    worksheet = (Excel.Worksheet)workbook.Worksheets[1];
                    workbook.Worksheets[1].Name = "Owner Contacts";
                }
                else if (startForm.excelActionFlag == "newExcelResults")
                {
                    string testFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "test";
                    workbook = (Excel.Workbook)app.Workbooks.Add(1);

                    worksheet = (Excel.Worksheet)workbook.Worksheets[1];
                    workbook.Worksheets[1].Name = "Event 1 Results";
                    //workbook.SaveAs(testFile, Missing.Value, Missing.Value, Missing.Value, false);
                    //workbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"Results", Missing.Value, Missing.Value, Missing.Value, false);



                    //workbook.SaveAs(startForm.excelFileLocation, Missing.Value, Missing.Value, Missing.Value, false);

                    //fileNameString = registrationForm.regFileLocation + "OB " + registrationForm.regClubName + " " + registrationForm.regDateString;
                }
                else if (dogForm.dogRegistrationExcel == "Yes")
                {
                    workbook = (Excel.Workbook)app.Workbooks.Add(1);
                    workbook.SaveAs(dogForm.filePath, Missing.Value, Missing.Value, Missing.Value, false);

                }
                else if (newFormString == "No")
                {

                    //workbook = app.Workbooks.Open(fileString, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    // workbook.Close(true,fileString,Missing.Value);
                    workbook = (Excel.Workbook)app.Workbooks.Open(fileString, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                }
                if (newFormString=="Yes"&registrationForm.formString=="OTR")
                {
                    //string sheetName = "Trial Report - " + dateString + " " + trialString;
                worksheet = (Excel.Worksheet)workbook.Worksheets[1];
                workbook.Worksheets[1].Name =trialReportForm.otrDateString+" Trial " + trialReportForm.otrTrialString;
                //workbook.Worksheets[1].Name = "Trial Report - " + dateString + " " + trialString;
                //workbook.Worksheets[1].Name = "Hello";
                //Excel.Name name1 = worksheet.Names.Add("Trial Report - " + dateString + " " + trialString, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                //worksheet.Name = "Trial Report - " + dateString + " " + trialString;


                }
                else if (newFormString == "Yes" & registrationForm.formString == "Registration")
                {
                    //string sheetName = "Trial Report - " + dateString + " " + trialString;
                    worksheet = (Excel.Worksheet)workbook.Worksheets[1];
                    workbook.Worksheets[1].Name = "Results: "+registrationForm.selectedEvent;
                    //workbook.Worksheets[1].Name = "Trial Report - " + dateString + " " + trialString;
                    //workbook.Worksheets[1].Name = "Hello";
                    //Excel.Name name1 = worksheet.Names.Add("Trial Report - " + dateString + " " + trialString, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    //worksheet.Name = "Trial Report - " + dateString + " " + trialString;


                }
                else if (startForm.excelActionFlag == "addExistingTrialReport")
                {
                    workbook = (Excel.Workbook)app.Workbooks.Open(startForm.excelFileLocation, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                   sheetCount = workbook.Worksheets.Count;
                   int sheetCountPlusONe=sheetCount+1;
                   worksheet = (Excel.Worksheet)workbook.Worksheets.Add(Missing.Value,workbook.Worksheets[sheetCount],Missing.Value,Missing.Value);
                   workbook.Worksheets[sheetCountPlusONe].Name = trialReportForm.trialReportDate + " Trial " + trialReportForm.trialReportTrialNumber;

                   //worksheet.Move(Missing.Value, workbook.Worksheets[sheetCount]);


                }
                else if (startForm.excelActionFlag == "existingExcelResults")
                {

                    workbook = (Excel.Workbook)app.Workbooks.Open(startForm.excelFileLocation, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    sheetCount = workbook.Worksheets.Count;
                    int sheetCountPlusONe = sheetCount + 1;
                    worksheet = (Excel.Worksheet)workbook.Worksheets.Add(Missing.Value, workbook.Worksheets[sheetCount], Missing.Value, Missing.Value);
                    workbook.Worksheets[sheetCountPlusONe].Name = "Event " + sheetCountPlusONe.ToString() + " Results";


                    //worksheet.Move(Missing.Value, workbook.Worksheets[sheetCount]);


                }
                else if (dogForm.dogRegistrationExcel == "Yes")
                {
                    worksheet = (Excel.Worksheet)workbook.Worksheets[1];
                    workbook.Worksheets[1].Name = dogForm.dogUKCNumber;
                }
            }
            catch (Exception e)
            {
                Console.Write("Error");
            }
             /* if (trialReportForm.saveMe=="Yes")
                {
                    workbook.Save();
                    workbook.Close();
                }
            */


        }


        public void createHeaders(int row, int col, string htext, string cell1,
        string cell2, int mergeColumns, string b, bool font, int size, string
        fcolor)
        {
            worksheet.Cells[row, col] = htext;
            workSheet_range = worksheet.get_Range(cell1, cell2);
            workSheet_range.Merge(mergeColumns);
            switch (b)
            {
                case "BLUE":
                    workSheet_range.Interior.Color = System.Drawing.Color.Red.ToArgb();
                    break;
                case "GAINSBORO":
                    workSheet_range.Interior.Color =
            System.Drawing.Color.Gainsboro.ToArgb();
                    break;
                //case "Turquoise":
                   // workSheet_range.Interior.Color =
            //System.Drawing.Color.Turquoise.ToArgb();
                    //break;
                case "PeachPuff":
                    workSheet_range.Interior.Color =
            System.Drawing.Color.PeachPuff.ToArgb();
                    break;
                default:
                    //  workSheet_range.Interior.Color = System.Drawing.Color..ToArgb();
                    break;
            }

            //workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
            //workSheet_range.Borders = null;
            workSheet_range.Font.Bold = font;
            workSheet_range.ColumnWidth = size;
            //workSheet_range.HorizontalAlignment = ContentAlignment.BottomCenter;
            if (startForm.excelActionFlag == "existingExcelResults" | startForm.excelActionFlag=="newExcelResults")
            {
                workSheet_range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
            }
            //workSheet_range.Cells.HorizontalAlignment = ContentAlignment.MiddleCenter;
            workSheet_range.Font.Color = System.Drawing.Color.FloralWhite.ToArgb();

        }

        public void addData(int row, int col, string data,
            string cell1, string cell2, string format)
        {
            worksheet.Cells[row, col] = data;
            workSheet_range = worksheet.get_Range(cell1, cell2);
            //workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
            workSheet_range.NumberFormat = format;
            workSheet_range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

            excelTimer.Tick += new EventHandler(excelTimer_Tick);
            excelTimer.Interval = 6000;
            excelTimer.Start();
        }
        void excelTimer_Tick(object sender, EventArgs e)
        {
            if (startForm.excelActionFlag != "ownerContacts")
            {
                if (startForm.excelActionFlag == "existingExcelResults" | startForm.excelActionFlag == "newExcelResults")
                {
                   /* Excel.Range sortRange;
                    sortRange = worksheet.get_Range("A14", "K32");
                    Excel.Range scoreColumn;
                    scoreColumn = worksheet.get_Range("C14", "C32");
                    sortRange.Sort(scoreColumn, Excel.XlSortOrder.xlDescending);*/
                    Excel.Range valueRange;
                    Excel.Range placeRange;
                    placeRange = worksheet.get_Range("A14", "A" + (14 + (registrationForm.numberofCompetitors - 1)).ToString());
                    valueRange = worksheet.get_Range("A14", "K"+(14+(registrationForm.numberofCompetitors-1)).ToString());
                    valueRange.Sort(valueRange.Columns[3, Type.Missing], Excel.XlSortOrder.xlDescending, Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlGuess, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal);
                    placeRange.Sort(placeRange.Columns[1, Type.Missing], Excel.XlSortOrder.xlAscending, Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlGuess, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal); 
                }
                // workbook.Close(true, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "Results.xls", Missing.Value);
/*
                GC.Collect(); 
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers(); 
                Marshal.FinalReleaseComObject(workSheet_range); 
                Marshal.FinalReleaseComObject(worksheet); 
                workbook.Close(Type.Missing, Type.Missing, Type.Missing); 
                Marshal.FinalReleaseComObject(workbook);
                app.Quit();
                Marshal.FinalReleaseComObject(app);

                */
                //workbook.Close(true, startForm.excelFileLocation, Missing.Value);
                workbook.SaveAs(startForm.excelFileLocation);
                workbook.Close();
                //app.Application.Quit();
                app.Quit();
                Marshal.ReleaseComObject(workSheet_range);
                Marshal.ReleaseComObject(worksheet);
                Marshal.ReleaseComObject(workbook);
                Marshal.ReleaseComObject(app);
                app = null;
                workbook = null;
                worksheet = null;
                workSheet_range = null;
                //Application.Exit();

                /* workSheet_range = null;
                 worksheet = null;
                 workbook = null;
                 app = null;*/
                //Thread.Sleep(5000);
                // File.Move(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "Results.xls", startForm.excelFileLocation);
            }

这意味着当执行excelTimer_Tick时, workbook值为nullstartForm不能为null,否则就会在if (startForm.excelActionFlag != "ownerContacts") )上出现错误。

我会在该行上放置一个断点并检查Watch窗口(或QuickWatch)是否为空。

要查看它为什么为空,可以将workbook字段重构为属性,并将该断点放入设置器中以查看它何时设置为null(或者在设置字段之前是否excelTimer_Tick )。

链接地址: http://www.djcxy.com/p/6065.html

上一篇: Can't disconnect form Excel Introp after saving created Excel File

下一篇: Problem with hanging interop COM objects