Janine

Janine

  • NA
  • 8
  • 41.5k

Export multiple dataGridViews to Excel

Sep 25 2010 6:26 AM

Hi, I am pretty new at this. I can export a dataGridView control to excel and it works fine, but what I want to do is Export mulitple dataGridViews to the same Excel Worksheet.
On a button click I add the dataGridView to an array and then on export click , I export the dataGridViews to excel. This works too, but in excel it puts the gridviews over eachother. i.e. all gridviews start in A1 of Excel. How to I get the gridviews to be placed underneath eachother in the same sheet?
I am using VS 2008 and coding in C#
here is some code I have for the export
Microsoft.Office.Interop.Excel.
Application wapp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.
Worksheet wsheet;
Microsoft.Office.Interop.Excel.
Workbook wbook;
wapp =
new Microsoft.Office.Interop.Excel.Application();
wapp.Visible =
false;
wbook = wapp.Workbooks.Add(
true);
wsheet = (Microsoft.Office.Interop.Excel.
Worksheet)wbook.ActiveSheet;

foreach(DataGridView item in Data)
{

try
{
for (int i = 0; i < item.Columns.Count; i++)
{
wsheet.Cells[1, i + 1] = item.Columns[i].HeaderText;

}

for (int i = 0; i < item.Rows.Count; i++)
{
DataGridViewRow row = item.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
DataGridViewCell cell = row.Cells[j];
try
{

wsheet.Cells[i+2, j + 1] = (cell.Value ==
null) ? "" : cell.Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}


catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}

}



wapp.UserControl =
true;
wapp.Visible =
true;

Answers (2)