Am working on a project and I need to export datagridview data into an excel sheet. My datagridview has 38 columns and about 120 rows(with spaces between the words) and the data is entered from the datagridview. When I run the app, I get this Exception, " Object reference not set to an instance of an object.". This is my code block:
private void exportbtn_Click(object sender, EventArgs e)
if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
{
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.AutoFit();
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
MessageBox.Show("Data Exported Successfully");
}
ExcelApp.ActiveWorkbook.SaveAs("");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Visible = true;
ExcelApp.Quit();
}
And I populated the datagridview first column(Facillity) as:
ArrayList row = new ArrayList();
row.Add("Techiman Holy Family Hospital"); dataGridView1.Rows.Add(row.ToArray());
row = new ArrayList();
row.Add("Opoku Agyeman Hospital"); dataGridView1.Rows.Add(row.ToArray());
row = new ArrayList();
row.Add("Kintampo Municipal Hospital"); dataGridView1.Rows.Add(row.ToArray());
Also I don't want to choose new excel workbook anytime am exporting to excel. I want to save all sheets in the same workbook. Is there a way to edit the following code to achieve that:
saveFileDialog1.InitialDirectory = ("C:");
saveFileDialog1.Title = "Save as Excel File";
saveFileDialog1.FileName = "";
saveFileDialog1.Filter = "Excel Files(2003)|*.xls| Excel Files(2007)|*.xlsx";
Please any help? Thanks.