I have to add the information of two DataGridViews in the same sheet of Excel consecutively. This is the code I have that only serves for a single DataGridView.
Microsoft.Office.Interop.Excel.Application
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1);
Microsoft.Office.Interop.Excel.Worksheet
ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
ws.Name = "Exported from gridview";
ws.Rows.HorizontalAlignment = HorizontalAlignment.Center;
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
ws.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
ws.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
// sizing the columns
ws.Cells.EntireColumn.AutoFit();
wb.SaveAs("c:\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.Quit();