Jump to content

A referência de objeto não foi definida como uma instância de um objecto.


Recommended Posts


Tenho o seguinte código:

    _Application excelApp;
            _Workbook excelWorkbook;
            _Worksheet excelWorksheet;

                excelApp = new Microsoft.Office.Interop.Excel.Application();
                excelWorkbook = excelApp.Workbooks.Add(Type.Missing);
                excelWorksheet = null;

                excelWorksheet = excelWorkbook.Sheets["Folha1"];
                excelWorksheet = excelWorkbook.ActiveSheet;
                //Excel Sheet Name
                excelWorksheet.Name = "Livro5";

                //Get DatagridView Header
                for (int i = 1; i < Tbl_ALL.Columns.Count; i++)
                    //Populating excel Header
                    excelWorksheet.Cells[1, i] = Tbl_ALL.Columns[i - 1].HeaderText;

                //Export DatagridView Rows
                for (int j = 0; j < Tbl_ALL.RowCount; j++)
                    for (int k = 0; k < Tbl_ALL.ColumnCount - 1; k++)
                        //Populating Excel Rows
                        excelWorksheet.Cells[j + 2, k + 1] = Tbl_ALL.Rows[j].Cells[k].Value.ToString();

                SaveFileDialog exportExcelFile = new SaveFileDialog();
                //Excel File Name
                exportExcelFile.FileName = "exportedExcelFile";
                //Default Excel Extension
                exportExcelFile.DefaultExt = "xlsx";

                if (exportExcelFile.ShowDialog() == DialogResult.OK)
                    //Saving Excel File To your Computer
                    excelWorkbook.SaveAs(exportExcelFile.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    //Message after excel file is saved
                    MessageBox.Show("Excel File Saved");

O problema é quando clico no botão de exportar, dá-me erro: a referência de objeto não foi definida como uma instância de um objecto.

Por baixo da zona comentada //Populating Excel Rows,

Conseguiria me ajudar?

Link to comment
Share on other sites

  • 2 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.