【问题标题】:Add Title before Export Excel在导出 Excel 前添加标题
【发布时间】:2013-10-16 09:17:24
【问题描述】:

我正在使用以下函数导出 Excel 文件。它工作正常。我将 SQL 数据库中的记录检索到数据表并导出 Excel 表。

        public ActionResult ExporttoExcel()
        {
            DataTable dt = new DataTable();
            SqlConnection con = new SqlConnection("Connection string here");
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from Exportxcel", con);
            dt.Load(cmd.ExecuteReader());
            int total = 0;
            foreach (DataRow row in dt.Rows)
            {
                int salaryvalue = Convert.ToInt32(row["Salary"]);
                total = salaryvalue + total;
            }
            dt.Rows.Add(new object[] { "", "Total", total });


            if (dt.Rows.Count > 0)
            {
                string filename = "ExcelExport.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();
                dgGrid.RenderControl(hw);
                Response.ContentType = "application/vnd.ms-excel";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
                Response.Write(tw.ToString());
                Response.End();
            }
             return View(dt);
        }

我的问题是我需要在值绑定之前添加两个标题?如何做到这一点?我需要添加标题,作者如下屏幕截图。如何做到这一点?

【问题讨论】:

    标签: asp.net asp.net-mvc excel c#-4.0 c#-3.0


    【解决方案1】:

    您可以在声明 System.Web.UI.HtmlTextWriter hw 后尝试添加它

    hw.Write("<table><tr><td colspan='3'>Title</td></tr>")
    hw.Write("<table><tr><td colspan='3'>Author</td></tr>")
    

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      相关资源
      最近更新 更多