2

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);
        }

ここに画像の説明を入力

私の質問は、Value Bind の前に 2 つのタイトルを追加する必要があることです。これを行う方法は?次のスクリーン ショットのように Title ,author を追加する必要があります。これを行う方法は?

ここに画像の説明を入力

4

1 に答える 1

3

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>")
于 2013-10-16T09:32:39.220 に答える