将gridview导出为.xls

时间:2012-04-20 05:51:33

标签: c# asp.net excel

我正在开发一个具有gridview控件的网页。我需要将数据传输到.xls格式。我能够创建.xls文件并传输数据,但问题是我需要在Excel工作表的背景中显示gridcells。现在,它只显示没有gridcells的空白背景。否则gridview转移得很好。由于此问题,打印.xls文件是一个问题。包含更多列的表不会压缩,而是打印2-3页。我的代码如下:

public static void ExportToXLS(string fileName, GridView gv,string companyName,string reportTitle , string period)
    {
        //For writing to XLS file
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {

                Table tableReport = new Table();
                tableReport.GridLines = gv.GridLines;

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    ReportList.PrepareControlForExport(gv.HeaderRow);
                    tableReport.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    ReportList.PrepareControlForExport(row);
                    tableReport.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    ReportList.PrepareControlForExport(gv.FooterRow);
                    tableReport.Rows.Add(gv.FooterRow);
                }

                //Takes value of company name
                System.Web.UI.WebControls.Label labelCompany = new System.Web.UI.WebControls.Label();
                labelCompany.Text = companyName;
                labelCompany.Font.Bold = true;

                //Takes value of report title
                System.Web.UI.WebControls.Label labelReport = new System.Web.UI.WebControls.Label();
                labelReport.Text = reportTitle;
                labelReport.Font.Bold = true;

                //Takes value of report period
                System.Web.UI.WebControls.Label labelPeriod = new System.Web.UI.WebControls.Label();
                labelPeriod.Text = period;

                //  render the htmlwriter into the response
                htw.Write("<center>");
                labelCompany.RenderControl(htw);
                htw.Write("<br/>");
                labelReport.RenderControl(htw);
                htw.Write("<br/>");
                labelPeriod.RenderControl(htw);
                htw.Write("</center>");
                htw.Write("<br/>");
                tableReport.RenderControl(htw);
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

有什么建议吗?

5 个答案:

答案 0 :(得分:1)

参考:Export grid

试试这个:

protected void btnExportExcel_Click(object sender, EventArgs e)

    {     

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

        Response.AddHeader("content-disposition",

         "attachment;filename=GridViewExport.xls");

        Response.Charset = "";

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

        StringWriter sw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(sw);

        grdExport.AllowPaging = false;

        oMailing.GetData(out ODs);

        grdExport.DataSource = ODs;

        grdExport.DataBind();

        //Change the Header Row back to white color

        grdExport.HeaderRow.Style.Add("background-color", "#FFFFFF");

        //Apply style to Individual Cells

        grdExport.HeaderRow.Cells[0].Style.Add("background-color", "green");

        grdExport.HeaderRow.Cells[1].Style.Add("background-color", "green");

        grdExport.HeaderRow.Cells[2].Style.Add("background-color", "green");

        grdExport.HeaderRow.Cells[3].Style.Add("background-color", "green");

        grdExport.HeaderRow.Cells[4].Style.Add("background-color", "green");

        grdExport.RenderControl(hw);

        //style to format numbers to string

        string style = @"<style> .textmode { mso-number-format:\@; } </style>";

        Response.Write(style);

        Response.Output.Write(sw.ToString());

        Response.Flush();

        Response.End();

    }

答案 1 :(得分:0)

  Response.Clear();
  Response.Buffer = true;
  Response.AddHeader("content-disposition",attachment;filename=GridViewExport.xls");
  Response.Charset = "";
  Response.ContentType = "application/vnd.ms-excel";

  StringWriter sw = new StringWriter();
  HtmlTextWriter hw = new HtmlTextWriter(sw);

答案 2 :(得分:0)

所有答案都能满足您的需求 - 您只是错过了格式化部分。

在一天结束时,您真正创建的是Excel可以读取的HTML文件(带有HTML表格)。 @BhaskarreddyMule中的RESPONSE标题是“强制”客户端将文件视为“xls”文件,如果它有Excel运行并打开它(但底线是它的不是真正的“本机”Excel文件

现在已经不在了,请用HTML思考。像在HTML中一样设置列,行和文本内容的样式。这就是你如何控制格式(即旧学校“nowrap”以防止包装单元格内容,字体大小等)。

我有一段时间没有这样做(当我需要这样做的时候,我已经转到了Excel XML和VB.Net XML文字)所以我不确定你对{{{{{{{{{ 1}} ...或者如果你必须进一步“旧学校”并从头开始构建HTML表格......

答案 3 :(得分:0)

首先请参阅:How to export nested gridview to excel/word with gridlines on the child grid,希望它能帮助您解决问题。

参考:How to export gridview to excel in a console type application?

您可以参考以下链接中的“导出到Excel”控件。这是一个自定义控件。希望它可以帮到你。

http://exporttoexcel.codeplex.com/

Styling exported grid

 protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;

            Response.AddHeader("content-disposition",
             "attachment;filename=GridViewExport.xls");

            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            grdExport.AllowPaging = false;
            oMailing.GetData(out ODs);
            grdExport.DataSource = ODs;
            grdExport.DataBind();

            //Change the Header Row back to white color
            grdExport.HeaderRow.Style.Add("background-color", "#FFFFFF");

            //Apply style to Individual Cells
            grdExport.HeaderRow.Cells[0].Style.Add("background-color", "green");

            grdExport.HeaderRow.Cells[1].Style.Add("background-color", "green");

            grdExport.HeaderRow.Cells[2].Style.Add("background-color", "green");

            grdExport.HeaderRow.Cells[3].Style.Add("background-color", "green");

            grdExport.HeaderRow.Cells[4].Style.Add("background-color", "green");

            for (int i = 0; i < grdExport.Rows.Count; i++)
            {
                GridViewRow row = grdExport.Rows;

                //Change Color back to white
                row.BackColor = System.Drawing.Color.White;

                //Apply text style to each Row
                row.Attributes.Add("class", "textmode");

                //Apply style to Individual Cells of Alternating Row
                if (i % 2 != 0)
                {
                    row.Cells[0].Style.Add("background-color", "#C2D69B");
                    row.Cells[1].Style.Add("background-color", "#C2D69B");
                    row.Cells[2].Style.Add("background-color", "#C2D69B");
                    row.Cells[3].Style.Add("background-color", "#C2D69B");
                    row.Cells[4].Style.Add("background-color", "#C2D69B");
                }

            }
            grdExport.RenderControl(hw);
            //style to format numbers to string
            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }

答案 4 :(得分:0)

我尝试使用export to excel,似乎你首先需要创建一个使用部分Excel = using Microsoft.Office.Interop.Excel,当你点击按钮时,只需创建一个包含工作簿和工作表属性的excel类,然后使用gridview属性Gridview.Row[].cell[].Text.,您可以将gridview中的每个值动态存储到工作表中,然后将其写入FILE ....