Saturday, 25 February 2012

Grid view to Excel in asp.net



// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "HMS_record";
// storing header part in Excel
for (int i = 1; i < GdvMainMaster.Columns.Count + 1; i++)
{
 worksheet.Cells[1, i] = GdvMainMaster.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i <= GdvMainMaster.Rows.Count - 1; i++)
{
for (int j = 0; j < GdvMainMaster.Columns.Count; j++)
{
 worksheet.Cells[i + 2, j + 1] = GdvMainMaster.Rows[i].Cells[j].Value.ToString();
}
}

No comments:

Post a Comment