如何将GridView导出到Excel?

时间:2016-07-27 10:24:10

标签: c#

我正在将GridView导出到Excel文件,但是当我打开文件时,首先我得到一个关于格式类型和扩展名不匹配的错误,当我打开它时,整个页面是带入Excel文件,而不仅仅是网格视图。

enter code here

  protected void ExportToExcel(object sender, EventArgs e)
        {
            try
            {
                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
                Response.Charset = "";
                Response.ContentType = "application/vnd.ms-excel";
                using (StringWriter sw = new StringWriter())
                {
                    HtmlTextWriter hw = new HtmlTextWriter(sw);

                    //To Export all pages
                    gridCustomer.AllowPaging = false;
                    //this.gridCustInfoBind(1);
                    gridCustAllInfoBind(1);

                    gridCustomer.HeaderRow.BackColor = Color.White;
                    foreach (TableCell cell in gridCustomer.HeaderRow.Cells)
                    {
                        cell.BackColor = gridCustomer.HeaderStyle.BackColor;
                    }
                    foreach (GridViewRow row in gridCustomer.Rows)
                    {
                        row.BackColor = Color.White;
                        foreach (TableCell cell in row.Cells)
                        {
                            if (row.RowIndex % 2 == 0)
                            {
                                cell.BackColor = gridCustomer.AlternatingRowStyle.BackColor;
                            }
                            else
                            {
                                cell.BackColor = gridCustomer.RowStyle.BackColor;
                            }
                            cell.CssClass = "textmode";
                        }
                    }

                    gridCustomer.RenderControl(hw);

                    //style to format numbers to string
                    string style = @"<style> .textmode { } </style>";
                    Response.Write(style);
                    Response.Output.Write(sw.ToString());
                    Response.Flush();
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Exception Message: " + ex.Message.Replace("'", "").Replace("\"", "") + "');", true);
            }
        }

3 个答案:

答案 0 :(得分:0)

看看doodlereport nuget包,我认为它适合你。

答案 1 :(得分:0)

以下代码会将您的数据表转换为Excel,因此您可以改为使用它:

textField.text

答案 2 :(得分:0)

使用Linq2Excel。它是一个开源工具,可在Nuget上使用。

https://github.com/paulyoder/LinqToExcel