The code I have below only takes data from one dynamically created tabpage (the default)‘s datagrid and exports it to a spreadsheet. I would like the application to take the data from all the dynamically created tabpages’ datagrids and export the data to excel and create a new worksheet for each tabpage as it is exporting.
Microsoft.Office.Interop.Excel._Application _appClass = new ApplicationClass();
_appClass.Visible = true;
_appClass.Caption = "Exported ECS Errors";
Microsoft.Office.Interop.Excel.Workbook wbk = _appClass.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet obj = (Worksheet)wbk.ActiveSheet;
// get the collection of sheets in the workbook
Microsoft.Office.Interop.Excel.Sheets sheets = wbk.Worksheets;
Range r = (Range)obj.Cells;
try
{
//Load the Headers and make them BOLD
for (int i = 0; i < ((DataGridView)this.dgOutput).Columns.Count; i++)
{
r[1, i + 1] = ((DataGridView)this.dgOutput).Columns[i].HeaderText.ToString();
((Range)r.Cells[1, i + 1]).Font.Bold = true;
}
//Load the data from the datagrid to the new spreadsheet
for (int i = 1; i < ((DataGridView)this.dgOutput).Rows.Count - 1; i++)
{
for (int j = 0; j < ((DataGridView)this.dgOutput).Columns.Count; j++)
{
r[i + 1, j + 1] = ((DataGridView)this.dgOutput).Rows[i].Cells[j].Value.ToString();
//Do the colors
if (((DataGridView)this.dgOutput).Rows[i].Cells[j].Value.ToString() == "Update OK")
{
((Range)r.Cells[i + 1, 1]).Font.Color = Color.Green.G;
}
}
}
}
catch (Exception EX) //user closes the Excel file while it is loading data from the datagrid
{
MessageBox.Show(EX.Message + "The Excel file was closed while loading data from the datagrid.",
"Error : Loading file!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}