Showing posts with label DataTable. Show all posts
Showing posts with label DataTable. Show all posts

Wednesday, May 15, 2013

How to export DataTable to Excel using C#

In this post we will be exporting the DataTable to an Excel using C#
Below is the method which will do the trick. Just pass the parameters datatable and the filename.

private void ExportDataTableToExcel(DataTable thetable, string fileName)
        {
            string attachment = "attachment; filename=" + fileName + ".xls";

            Response.ClearContent();

            Response.AddHeader("content-disposition", attachment);

            Response.ContentType = "application/vnd.ms-excel";

            //write columns from DataTable to Excel      
            string tab = "";
            foreach (DataColumn dc in thetable.Columns)
            {
                string title = string.Empty;
                if (dc.ColumnName.Contains("Meta"))
                    title = "Metadata Properties";
                else
                    title = dc.ColumnName;
                Response.Write(tab + title);
                tab = "\t";
            }
            Response.Write("\n");

            //write rows from DataTable to Excel  
            int i;
            foreach (DataRow dr in thetable.Rows)
            {
                tab = "";
                for (i = 0; i < thetable.Columns.Count; i++)
                {
                    Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            //To throw the excel file generated
            Response.End();

        }


Hope this helps...

Thursday, January 12, 2012

How to filter a DataTable using LINQ

Hi Friends,

In this post we are going to Filter a DataTable using LINQ.

We can filter a DataTable in many ways but using LINQ is the best and recommended approach..
In the below code snippet we are going to filter the datatable and then assign the results back to it.

Below are the assumptions before you jump into the code.
  • dtMainTable is the DataTable which you got it from your logic.

var tempTable = from DataRow dataRow in dtMainTable.Rows
                                    where dataRow["ColumnName"] == "Value"
                                    select dataRow;
                    if (tempTable.Count() > 0)
                    {
                        dtMainTable= tempTable.CopyToDataTable();
                        dtMainTable.AcceptChanges();
                    }

Hope this helps...

Popular Posts