在导出Excel之前添加标题

正在使用以下函数导出Excel文件。它工作正常。我从SQL数据库检索logging到数据表,并导出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); } 

在这里输入图像说明

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

在这里输入图像说明

你可以试着在声明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>")