datagrid|excel| Program | data | show
<summary>
Import the data from the DataGrid into Excel and display the Excel application.
Note Calling this method must have an Excel 2000 application installed, and assume that the DataGrid is bound to a dataset
</summary>
<param name= "Grid" ></param>
<param name= "Reporttitle" ></param>
public static void Exportdatagridtoexcel (DataGrid grid,string reporttitle)
{
DataTable myTable = (DataSet) grid. DataSource). Tables[0];
Try
{
Excel.Application xlapp = new Excel.applicationclass ();
int rowIndex;
int colindex;
RowIndex = 2;
Colindex = 0;
Excel.Workbook xlbook =xlapp.workbooks.add (true);
if (grid. Tablestyles.count >0)
{
Excel.Range Range = Xlapp.get_range (Xlapp.cells[1,1],xlapp.cells[1,grid. Tablestyles[0]. Gridcolumnstyles.count]);
Range. MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = Reporttitle;
XlApp.ActiveCell.Font.Size = 18;
XlApp.ActiveCell.Font.Bold = true;
foreach (DataGridColumnStyle Colu in grid. Tablestyles[0]. GridColumnStyles)
{
Colindex=colindex +1;
Xlapp.cells[2,colindex] = Colu. HeaderText;
}
All rows of the resulting table, assigned to cells
for (int row = 0;row < mytable.rows.count;row++)
{
RowIndex = RowIndex + 1;
Colindex = 0;
for (int col=0;col<grid. Tablestyles[0]. gridcolumnstyles.count;col++)
{
Colindex = Colindex + 1;
Xlapp.cells[rowindex, Colindex] = Grid[row,col]. ToString ();
}
}
}
Else
{
Excel.Range Range = Xlapp.get_range (Xlapp.cells[1,1],xlapp.cells[1,mytable.columns.count]);
Range. MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = Reporttitle;
XlApp.ActiveCell.Font.Size = 18;
XlApp.ActiveCell.Font.Bold = true;
Fill in the first row of Excel with the field names in the table
foreach (DataColumn Col in Mytable.columns)
{
Colindex = Colindex + 1;
Xlapp.cells[2, Colindex] = col.columnname;
}
All rows of the resulting table, assigned to cells
for (int row = 0;row < mytable.rows.count;row++)
{
RowIndex = RowIndex + 1;
Colindex = 0;
for (int col=0;col<mytable.columns.count;col++)
{
Colindex = Colindex + 1;
Xlapp.cells[rowindex, Colindex] = Grid[row,col]. ToString ();
}
}
}
Xlapp.get_range (xlapp.cells[2, 1], xlapp.cells[2, Colindex]). Font.Bold = true;
Xlapp.get_range (xlapp.cells[2, 1], Xlapp.cells[rowindex, Colindex]). Borders.LineStyle = 1;
XlApp.Cells.EntireColumn.AutoFit ();
XlApp.Cells.VerticalAlignment = Excel.Constants.xlCenter;
XlApp.Cells.HorizontalAlignment = Excel.Constants.xlCenter;
Xlapp.visible = true;
}
catch (Exception e)
{
Throw e;
}
}