Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

recently started to code in vs2010 from vs2005. need a code to export to excel from a datagrid. in vs2005 the following code was used.

    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=dgd.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.xls";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    dgd.Visible = true;
    dgd.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();

this does not yield the same result in vs2005. the header is not aligned to the column. the pictures in the datagrid is not fetched in excel and the links in the datagrid does not appear properly. please suggest a better code.

share|improve this question
add comment

4 Answers

Add following code after htmlwriter line


`if (dtDetails.Rows.Count > 0)
            {
                for (int i = 0; i < gvProduction.HeaderRow.Cells.Count; i++)
                {
                    gvProduction.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
                }
                int j = 1;
                //This loop is used to apply stlye to cells based on particular row
                foreach (GridViewRow gvrow in gvProduction.Rows)
                {
                    gvrow.BackColor = Color.White;
                    if (j <= gvProduction.Rows.Count)
                    {
                        if (j % 2 != 0)
                        {
                            for (int k = 0; k < gvrow.Cells.Count; k++)
                            {
                                gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                            }
                        }
                    }
                    j++;
                }
                gvProduction.RenderControl(hw);
                Response.Write(sw.ToString());
                Response.End();
            }`
share|improve this answer
add comment

you can use following code : on export button click:

FileInfo FI = new FileInfo(Path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid DataGrd = new DataGrid();
DataGrd.DataSource = dt1;
DataGrd.DataBind();

DataGrd.RenderControl(htmlWrite);
string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
if (!Directory.Exists(directory))
{
    Directory.CreateDirectory(directory);
}

System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
stringWriter.ToString().Normalize();
vw.Write(stringWriter.ToString());
vw.Flush();
vw.Close();
WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());

Code for writing attachment:

public static void WriteAttachment(string FileName, string FileType, string content)
{
   HttpResponse Response = System.Web.HttpContext.Current.Response;
   Response.ClearHeaders();
   Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
   Response.ContentType = FileType;
   Response.Write(content);
   Response.End();
}

For more reference you can visit:

http://www.codeproject.com/Tips/477436/Export-Gridview-Data-to-Excel-in-ASP-NET

share|improve this answer
add comment

Below code may help you to write an excel sheet using gridview.

    // function to export datagridview to excel sheet
    // excel_file contains the path to the excel file.
    public void export_to_excel(DataGridView dgv, string excel_file)
    {
        int cols;
        //open file
        StreamWriter wr = new StreamWriter(excel_file);
        //determine the number of columns and write columns to file
        cols = dgv.Columns.Count;
        for (int i = 0; i < cols; i++)
        {
            wr.Write(dgv.Columns[i].HeaderText.ToString().ToUpper() + "\t");
        }
        wr.WriteLine();
        //write rows to excel file
        for (int i = 0; i < (dgv.Rows.Count - 1); i++)
        {
            for (int j = 0; j < cols; j++)
            {
                if (dgv.Rows[i].Cells[j].Value != null)
                    wr.Write(dgv.Rows[i].Cells[j].Value + "\t");
                else
                {
                    wr.Write("\t");
                }
            }
            wr.WriteLine();
        }
        //close file
        wr.Close();
    }

Also you can go through this link, this might also help you..

http://blogs.msdn.com/b/erikaehrli/archive/2009/01/30/how-to-export-data-to-excel-from-an-asp-net-application-avoid-the-file-format-differ-prompt.aspx

I hope it will help you. :)

share|improve this answer
add comment

I am using same in our project.

 private void ExportToExcel(DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            string filename = "DownloadReport.xls";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            dgGrid.DataSource = dt;
            dgGrid.DataBind();

            //Get the HTML for the control.
            dgGrid.RenderControl(hw);
            //Write the HTML back to the browser.
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
            this.EnableViewState = false;
            Response.Write(tw.ToString());
            Response.End();
        }
    }

Hope it helps you

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.