Trouble while Exporting GridView Data in Excel C#

Having trouble while exporting the gridview data in excel. It is exporting the whole page not Gridview data.

My Code as below :

        Response.Clear();
        Response.Buffer = true;
        Response.ClearContent();
        Response.ClearHeaders();
        Response.Charset = "";
        StringWriter strwritter = new StringWriter();
        HtmlTextWriter htmlwritter = new HtmlTextWriter(strwritter);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/ms-excel";
        Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", "DSR"+DateTime.Now.ToString("dd-MM-yyyy")+".xls"));
        GridView1.GridLines = GridLines.Both;
        GridView1.HeaderStyle.Font.Bold = true;
        GridView1.RenderControl(htmlwritter);
        Response.Write(strwritter.ToString());
        Response.End();

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can try doing something like that. Simple and straightforward.

    Response.Clear();
    Response.Buffer = true;
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Charset = "";
    StringWriter strwritter = new StringWriter();
    HtmlTextWriter htmlwritter = new HtmlTextWriter(strwritter);
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter strwritter = new StringWriter();
    HtmlTextWriter htmlwritter = new HtmlTextWriter(strwritter);
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/ms-excel";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", "DSR"+DateTime.Now.ToString("dd-MM-yyyy")+".xls"));
    GridView1.RenderBeginTag(htmlwritter);
    GridView1.HeaderRow.RenderControl(htmlwritter);
    foreach (GridViewRow row in GridView1.Rows)
    {
        row.RenderControl(htmlwritter);
    }
    GridView1.FooterRow.RenderControl(htmlwritter);
    GridView1.RenderEndTag(htmlwritter);
    Response.Write(strwritter.ToString());
    Response.End();

Method 2

A simple solution to this problem is to get your C# code to write the GridView‘s data source to an Excel file.

Here’s the C# library I wrote to do exactly that:
Export to Excel

All source code is provided free of charge, and you just need to add a few lines to your ASP.Net code:

// The following ASP.Net code gets run when I click on my "Export to Excel" button.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
    // It doesn't get much easier than this...
    CreateExcelFile.CreateExcelDocument(listOfEmployees, "Employees.xlsx", Response);
}

The other advantage of this is that it’ll create a “real” .xlsx file (using the OpenDocument library). The downside is that those Microsoft libraries weigh-in at about 5Mb.

Method 3

Try this,it will work..

private void Export_To_Excel()          
{

        Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

        try
        {
            worksheet = workbook.ActiveSheet;

            worksheet.Name = "ExportedFromDatGrid";

            int cellRowIndex = 1;
            int cellColumnIndex = 1;
            ////Loop through each row and read value from each column. 
            for (int i = 0; i < this.dGV.Rows.Count - 1; i++)
            {
                for (int j = 0; j < this.dGV.Columns.Count; j++)
                {
                    //// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check. 
                    if (cellRowIndex == 1)
                    {
                        worksheet.Cells[cellRowIndex, cellColumnIndex] = this.dGV.Columns[j].HeaderText;
                        worksheet.Cells[cellRowIndex, cellColumnIndex].Font.FontStyle = FontStyle.Bold;
                    }
                    else
                    {
                        worksheet.Cells[cellRowIndex, cellColumnIndex] = this.dGV.Rows[i].Cells[j].Value.ToString();
                    }

                    cellColumnIndex++;
                }

                cellColumnIndex = 1;
                cellRowIndex++;
            }

            worksheet.Columns.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            worksheet.Columns.AutoFit();

            ////Getting the location and file name of the excel to save from user. 
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx";
            saveDialog.FilterIndex = 2;

            if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                workbook.SaveAs(saveDialog.FileName);
                MessageBox.Show("Export Successful", "Info", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            }
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
        }
        finally
        {
            excel.Quit();
            workbook = null;
            excel = null;
        }
    }

Method 4

Here an example that uses EPPlus. Just input a SQL query (or stored procedure name) and a filename to exportToExcel and you’ll get an Excel file.
exportToExcel("SELECT * FROM yourTable", "myFileName");

    using OfficeOpenXml;
    using OfficeOpenXml.Style;
    using System;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Globalization;
    using System.Web;

    //=== create an excel document =========================================
    public static void exportToExcel(string sqlQuery, string fileName)
    {
        HttpResponse Response = HttpContext.Current.Response;
        DataTable dt = loadExternalDataTable(sqlQuery);

        using (ExcelPackage p = new ExcelPackage())
        {
            //create a new workbook
            p.Workbook.Properties.Author = "VDWWD";
            p.Workbook.Properties.Title = fileName;
            p.Workbook.Properties.Created = DateTime.Now;

            //create a new worksheet
            p.Workbook.Worksheets.Add(fileName);
            ExcelWorksheet ws = p.Workbook.Worksheets[1];
            ws.Name = fileName;
            ws.Cells.Style.Font.Size = 11;
            ws.Cells.Style.Font.Name = "Calibri";

            createExcelHeader(ws, dt);
            createExcelData(ws, dt);

            ws.Cells[ws.Dimension.Address].AutoFitColumns();

            //make all columms just a bit wider, they would sometimes not fit
            for (int col = 1; col <= ws.Dimension.End.Column; col++)
            {
                ws.Column(col).Width = ws.Column(col).Width + 1;
            }

            //send the file to the browser
            byte[] bin = p.GetAsByteArray();
            Response.ClearHeaders();
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-length", bin.Length.ToString());
            Response.AddHeader("content-disposition", "attachment; filename="" + fileName + ".xlsx"");
            Response.OutputStream.Write(bin, 0, bin.Length);
            Response.Flush();
            Response.Close();
            Response.End();
        }
    }


    //=== create the excel sheet header row =========================================
    private static void createExcelHeader(ExcelWorksheet ws, DataTable dt)
    {
        int colindex = 1;

        //loop all the columns
        foreach (DataColumn dc in dt.Columns)
        {
            var cell = ws.Cells[1, colindex];

            //make the text bold
            cell.Style.Font.Bold = true;

            //make the background of the cell gray
            var fill = cell.Style.Fill;
            fill.PatternType = ExcelFillStyle.Solid;
            fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF"));

            //fill the cell with the text
            cell.Value = dc.ColumnName.ToUpper();

            colindex++;
        }
    }


    //=== create the excel sheet data =========================================
    private static void createExcelData(ExcelWorksheet ws, DataTable dt)
    {
        int colindex = 0;
        int rowindex = 1;

        //loop all the rows
        foreach (DataRow dr in dt.Rows)
        {
            colindex = 1;
            rowindex++;

            //loop all the columns
            foreach (DataColumn dc in dt.Columns)
            {
                var cell = ws.Cells[rowindex, colindex];
                string datatype = dc.DataType.ToString();

                //fill the cell with the data in the correct format, needs to be done here because the headder row makes every column a string otherwise
                if (datatype == "System.Decimal" || datatype == "System.Double" || datatype == "System.Float")
                {
                    if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                        cell.Value = Convert.ToDecimal(dr[dc.ColumnName]);

                    cell.Style.Numberformat.Format = "0.00";
                }
                else if (datatype == "System.Int16" || datatype == "System.Int32" || datatype == "System.Int64" || datatype == "System.Long")
                {
                    if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                        cell.Value = Convert.ToInt64(dr[dc.ColumnName]);
                }
                else if (datatype == "System.Bool" || datatype == "System.Boolean")
                {
                    if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                        cell.Value = Convert.ToBoolean(dr[dc.ColumnName]); ;
                }
                else if (datatype == "System.DateTime")
                {
                    if (!string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                        cell.Value = Convert.ToDateTime(dr[dc.ColumnName]);

                    cell.Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
                }
                else
                {
                    cell.Value = dr[dc.ColumnName];
                }

                colindex++;
            }
        }
    }


    //=== create a datatable from a query  =========================================
    public static DataTable loadExternalDataTable(string sqlQuery)
    {
        DataTable dt = new DataTable();

        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
        using (SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, connection))
        {
            try
            {
                adapter.Fill(dt);
            }
            catch
            {
            }
        }

        return dt;
    }

Method 5

This code may be help you

        protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        BindData();
        GridView1.Visible = true;

        string FileName = "Deal Report_(" + DateTime.Now.AddHours(5).ToString("yyyy-MM-dd") + ").xls";

        Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition",
         "attachment;filename=" + FileName);
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        GridView1.HeaderRow.Style.Add("color", "#FFFFFF");
        GridView1.HeaderRow.Style.Add("background-color", "#1F437D");

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            row.BackColor = System.Drawing.Color.White;
            row.Attributes.Add("class", "textmode");
            if (i % 2 != 0)
            {
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    //row.Cells[j].Style.Add("background-color", "#eff3f8");
                }
            }
        }
        GridView1.RenderControl(hw);
        string style = @"<style> .textmode { mso-number-format:@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.End();
        GridView1.Visible = false;
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x