dreamheart
dreamheart

Reputation: 63

Application stop when exporting data to excel

I have a code that displays a table from an Access database, on my WinForm I have an option to export the table to excel, once the user click on it takes some time to copy all rows to excel, if the user try to close the excel before all cells get transfer to the sheet the application will stop and throw the error System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800AC472'

Here is the code for the "Export to Excel" button I have in my windows form

        private void Export_btn_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
        app.Visible = true;
        worksheet = workbook.Sheets["Sheet1"];
        worksheet = workbook.ActiveSheet;
        for (int i = 1; i < fviAoi_tbl.Columns.Count + 1; i++)
        {
            worksheet.Cells[1, i] = fviAoi_tbl.Columns[i - 1].HeaderText;
        }
        for (int i = 0; i < fviAoi_tbl.Rows.Count - 1; i++)
        {
            for (int j = 0; j < fviAoi_tbl.Columns.Count; j++)
            {
                if (fviAoi_tbl.Rows[i].Cells[j].Value != null)
                {
                    worksheet.Cells[i + 2, j + 1] = fviAoi_tbl.Rows[i].Cells[j].Value.ToString();
                }
                else
                {
                    worksheet.Cells[i + 2, j + 1] = "";
                }
            }
        }
    }

Any ideas why this is happening or how can I make my application to ignore that error and continue running.

Upvotes: 1

Views: 796

Answers (2)

Vityata
Vityata

Reputation: 43593

In general, Null is probably not what you think it is. Null is not 0 nor empty string. Null is lack of data. What is the difference between ("") and (null)

Thus, C# and .NET probably throws an error here:

if (fviAoi_tbl.Rows[i].Cells[j].Value != null) because, it does not understand how can you compare some Excel cell with Null and what should it answer. Change the code to:

if (fviAoi_tbl.Rows[i].Cells[j].Value != "" or something similar.

Upvotes: 1

Jon Lopez Garcia
Jon Lopez Garcia

Reputation: 237

Surround the code line that emit the exception with a try... catch...

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/

Upvotes: 2

Related Questions