Skip to content

Getting Specific Data in DataSet Column and export in excel

gully fretilop

Asked Feb 4, 2015, 4:48 PM EST1 answer
Share
LinkedInX
i have 5 column in my dataset.
name, age,sex, address and contact number
then i have 3 datarows in dataset

i need only name, address and contact number during export in excel..
how can i do that?
im using the using Excel = Microsoft.Office.Interop.Excel;
i only get the 1st row.. not all rows in data set

this is my code for getting the values
 
C#
 Microsoft.Office.Interop.Excel.Application ExcelAp = new Microsoft.Office.Interop.Excel.Application();
                        ExcelAp.Application.Workbooks.Add(Type.Missing);
                        ExcelAp.Columns.ColumnWidth = 25;

int i =0;
foreach( DataRow datarow in DsNow.Tables[0].Rows)
{
      for(i = 0; DsNow.Tables[0].Rows.Count - 1; i ++)
            {
                         ExcelAp.Cells[i + 6, 1] = datarow["name"].ToString();
                         ExcelAp.Cells[i + 6, 2] = datarow["address"].ToString();
                         ExcelAp.Cells[i + 6, 3] = datarow["contactnumber"].ToString();
            }
}
 
please help 

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Jayakumar J
    0
    Instead of using Interop, you can use the following code for excel export with required columns.  On button click you will be prompted to save the exported excel.


    protected void btnExport_Click(object sender, EventArgs e)
        {      
            string attachment = "attachment; filename=ExportedExcel.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";        
            DataTable dt = DsNow.Tables[0];
            //Remove the columns that are not required
            dt.Columns.Remove("ColumnName1")
            dt.Columns.Remove("ColumnName2")
            DataView dv = new DataView();
            dv = dt.DefaultView;
            GridView GvExcel = new GridView();
            GvExcel.DataSource = dv ;
            GvExcel.DataBind();
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GvExcel.RenderControl(htw);
            Response.Write(sw.ToString()); 
            Response.End();
        }

    Note: If the number of columns to be removed are more, then create new Datatable with required number of columns to be exported using existing DataTable
    0