【问题标题】:Export to excel from Gridview with color codes使用颜色代码从 Gridview 导出到 excel
【发布时间】:2014-03-10 04:55:59
【问题描述】:

我在GridView 中使用基于某些百分比逻辑的颜色代码。但是在导出到Excel 时,我不知道如何在Excel 中维护这个颜色代码。请指导

下面是RowDataBound的代码

protected void Grd_QADetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var dataRowView = e.Row.DataItem as DataRowView;
            DataRow row = dataRowView.Row;

            var Current = (row["Current Month Percentage"] as double?) ?? null;

            double? Yellow = (double?)Convert.ToDouble(row["Yellow"]);
            double? Green = (double?)Convert.ToDouble(row["Green"]);

            if (Current != null)
            {
                if (Current >= Green)
                    e.Row.Cells[6].BackColor = Color.Green;

                if (Current >= Yellow && Current < Green)
                    e.Row.Cells[6].BackColor = Color.Yellow;

                if (Current < Yellow)
                    e.Row.Cells[6].BackColor = Color.Red;
            }               
        }
    }

下面是Export to Excel的代码

private void ExportthroughWeb(DataTable dt, string FileName)
    {
        try
        {
            if (dt.Rows.Count > 0)
            {
                string filename = FileName + ".xls";

                using (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("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">" + Environment.NewLine);
                    Response.Write(tw.ToString());

                    Response.Write("</body>");
                    Response.Write("</html>");

                    Response.End();
                }
            }
        }

【问题讨论】:

  • @Raghu..您在导出到 excel 时没有获得颜色代码,是否调用了 RowDataBound?你能提供更多信息吗..
  • @AvinashKothamasu Gridview 显示颜色代码。但是在Excel 之后Export 我想保持这些颜色逻辑。我不知道如何实现它...
  • @Raghu..当前你得到的网格没有使用上述颜色,对吗?
  • 我在ASP.NET GridView 中获得颜色...我对此没有问题.. 我有一个按钮调用函数ExportthroughWeb(),它将DataTable dt 值导出到Excel 我需要这些颜色代码..
  • 在导出时,您是否会失去颜色?

标签: c# asp.net excel gridview export-to-excel


【解决方案1】:

您需要为RowDataBound附加一个事件处理程序

请将您的代码修改如下:

private void ExportthroughWeb(DataTable dt, string FileName)
    {
        try
        {
            if (dt.Rows.Count > 0)
            {
                string filename = FileName + ".xls";

                using (System.IO.StringWriter tw = new System.IO.StringWriter())
                {
                    System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
                    GridView dgGrid = new GridView();
                    dgGrid.DataSource = dt;
                    dgGrid.RowDataBound += new GridViewRowEventHandler(Grd_QADetails_RowDataBound);
                    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("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">" + Environment.NewLine);
                    Response.Write(tw.ToString());

                    Response.Write("</body>");
                    Response.Write("</html>");

                    Response.End();
                }
            }

希望这会有所帮助..

我的测试示例:更新

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="webapp1._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:GridView runat="server" ID="grdDetails" OnRowDataBound="Grd_QADetails_RowDataBound">

    </asp:GridView>
    <asp:Button  runat="server" ID="btnSubmit" OnClick="ExportToGrid"/>
</asp:Content>

背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;

namespace webapp1
{
    public partial class _Default : System.Web.UI.Page
    {

        DataTable dtDetails = new DataTable();


        protected void Grd_QADetails_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var dataRowView = e.Row.DataItem as DataRowView;
                DataRow row = dataRowView.Row;

                var Current = (row["Dosage"] as int?) ?? null;


                if (Current != null)
                {
                    if (Current >= 1 && Current < 10)
                        e.Row.Cells[1].BackColor = Color.Green;

                    else if (Current >= 10 && Current < 20)
                        e.Row.Cells[1].BackColor = Color.Yellow;

                    else
                        e.Row.Cells[1].BackColor = Color.Red;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {


            dtDetails.Columns.Add("Dosage", typeof(int));
            dtDetails.Columns.Add("Drug Suggested", typeof(string));
            dtDetails.Columns.Add("Patient Name", typeof(string));
            dtDetails.Columns.Add("Date", typeof(DateTime));
            dtDetails.Columns.Add("Type", typeof(string));
            dtDetails.Columns.Add("Payment Mode", typeof(string));
            dtDetails.Columns.Add("Appointment Status", typeof(string));
            dtDetails.Columns.Add("Location", typeof(string));

            dtDetails.Rows.Add(1, "Indocin", "David", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(2, "Enebrel", "Sam", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(3, "Hydralazine", "Christoff", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(4, "Combivent", "Janet", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(5, "Dilantin", "Melanie", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");

            dtDetails.Rows.Add(6, "Indocin", "David", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(7, "Enebrel", "Sam", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(8, "Hydralazine", "Christoff", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(9, "Combivent", "Janet", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(10, "Dilantin", "Melanie", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");

            dtDetails.Rows.Add(11, "Indocin", "David", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(12, "Enebrel", "Sam", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(13, "Hydralazine", "Christoff", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(14, "Combivent", "Janet", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(15, "Dilantin", "Melanie", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");

            dtDetails.Rows.Add(16, "Indocin", "David", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(17, "Enebrel", "Sam", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(18, "Hydralazine", "Christoff", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(19, "Combivent", "Janet", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(20, "Dilantin", "Melanie", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");

            dtDetails.Rows.Add(21, "Indocin", "David", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(22, "Enebrel", "Sam", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(23, "Hydralazine", "Christoff", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(24, "Combivent", "Janet", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");
            dtDetails.Rows.Add(25, "Dilantin", "Melanie", DateTime.Now, "Casuality", "Cash", "Pending", "Kolkatta");

            if (!IsPostBack)
            {
                grdDetails.DataSource = dtDetails;
                grdDetails.DataBind();
            }

        }

        protected void ExportToGrid(object sender, EventArgs e)
        {

            ExportToGrid(dtDetails);
        }

        private void ExportToGrid(DataTable dt)
        {

            if (dt.Rows.Count > 0)
            {
                string filename = "Avinash" + ".xls";

                using (System.IO.StringWriter tw = new System.IO.StringWriter())
                {
                    System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
                    GridView dgGrid = new GridView();
                    dgGrid.DataSource = dt;
                    dgGrid.RowDataBound += new GridViewRowEventHandler(Grd_QADetails_RowDataBound);
                    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("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">" + Environment.NewLine);
                    Response.Write(tw.ToString());

                    Response.Write("</body>");
                    Response.Write("</html>");

                    Response.End();
                }
            }
        }

    }![enter image description here][1]
}

【讨论】:

  • 在编译过程中出现错误提示“System.Web.UI.WebControls.DataGrid”不包含“RowDataBound”的定义,并且没有扩展方法“RowDataBound”接受第一个参数”
  • 是的,我确实在您回复之前尝试过使用GridView。但是当我将它更改为 Gridview 时,我在 Excel 中没有得到任何值。它都是空白的!
  • @Raghu..上面是示例示例..我已经测试过..我不确定您的代码有什么问题。但这是为我解决的问题..as你可以在上图中看到
  • 我再次尝试使用新网页,但它再次变为空白。虽然我收到一条错误消息“无法评估表达式,因为代码已优化或本机框架位于调用堆栈顶部”,但我已使用 catch (System.Threading.ThreadAbortException lException) { string str = lException.Message 处理; }
  • @Raghu..你试过调试吗..你在哪一行得到错误?
【解决方案2】:

这里是您会发现有用的链接。只需相应地更改您的颜色条件。 http://gridview-excel.blogspot.in/2011/12/gridview-to-excel-in-aspnetc.html

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    相关资源
    最近更新 更多