dimanche 28 juin 2015

Export .NET DataTable to Microsoft Excel and Format Results

I want to set the row height with eporting my data to Excel. I tried the below, but am getting a debug error of

Unable To Cast object type of 'System.Web.UI.WebControls.DataGridItem' to type 'System.Web.UI.WebControls.GridViewRow'

And this is my syntax

public void ExportToExcel(DataTable dataTable)
{
  string filename = "Bamo.xls";
  StringWriter tw = new System.IO.StringWriter();
  HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
  DataGrid dgGrid = new DataGrid();
  dgGrid.DataSource = dataTable;
  dgGrid.DataBind();
  int j = 0;
  foreach(GridViewRow gvrow in dgGrid.Items)
  {
    if (j % 2 != 0)
    {
        for (int k = 0; k < gvrow.Cells.Count; k++)
        {
            gvrow.Cells[k].Style.Add("Height", "10");
        }
    }
    j++;
  }
}

Aucun commentaire:

Enregistrer un commentaire