Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8741463
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T11:19:14+00:00 2026-06-13T11:19:14+00:00

I am trying to save an excel file that was created and written to

  • 0

I am trying to save an excel file that was created and written to via a C# application using the Excel Interop. I have looked all over this site as others to find a code that properly works and I have yet to find one. My excel interop funciton uses a workbook, worksheet, app, and workshee_range object. Does anyone have any suggestions. The easier the solution the better. I’m a beginner to intermediate level C# programmer and an advanced solution will likely be out of my scope of knowledge. The unhandled exception I am getting when trying to disconnect from the excel interop after saving and then closting the excel file says ‘Object reference not set to an instance of an object.’

here is the code I am using to do the aforementioned process:

            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;

Here is the full bit of code:

     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);
            }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T11:19:15+00:00Added an answer on June 13, 2026 at 11:19 am

    This means that when excelTimer_Tick is executed, the value of workbook is null (startForm can’t be null, because otherwise you would have the error on if (startForm.excelActionFlag != "ownerContacts")).

    I’d put a breakpoint on that line and check in the Watch window (or QuickWatch) whether it’s null or not.

    To see why it’s null, you can refactor your workbook field into a property and put the breakpoint in the setter to see when it’s set to null (or whether excelTimer_Tick is called before the field is set).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using Excel 2010. I'm trying so save my excel file, with this code.
i have a VSTO application(WPF) which can save an opened Excel File on a
We have created a web application, using ASP.NET, that allows users to upload documents
When trying to save the database using boost serialization, I encounter the segfault that
I'm trying to save my Photo class that has a byte[] File field. When
I'm trying to create a batch file that will convert an Excel file to
I am trying to communicate with Excel from a Java/SWT application. I have been
I have on excel file that has the data of my student table. Now
I am trying to download Excel file from site using Selenium. The way I'm
I'm trying to save Excel files into the database, I do not want to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.