使用带有单独标题字段的C#将数据导出到Excel

时间:2014-03-06 06:33:56

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

我必须将一些数据导出到excel。我已经完成了导出数据,这些数据来自sql查询并将它们绑定到网格视图,然后将该网格视图导出为ex​​cel。它工作正常。

但问题是当excel表格中显示一些其他信息时,如下所示(报告日期,样式名称),如何将它们添加到excel表格的顶部我的数据清单。

Sample Format

是否有任何库可以执行此操作.. Plzz帮助...

这是一个ASP.NET应用程序。

3 个答案:

答案 0 :(得分:1)

查看Epplus库。

您可以轻松地将SQL查询返回的结果集绑定到工作表,并在所需位置插入新行。

private void DumpExcel(DataTable tbl)
{
   using (ExcelPackage pck = new ExcelPackage())
   {
     //Create the worksheet
     ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");


     //Load the datatable into the sheet, starting from cell A1.
     ws.Cells["A1"].LoadFromDataTable(tbl, true);
     ExcelWorksheet.InsertRow(int rowFrom, int rows, intCopyStylesFromRow);

     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
     Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
     Response.BinaryWrite(pck.GetAsByteArray());
    }
 }

答案 1 :(得分:0)

有几个库可以做到这一点。我试过这个npoi dll

你可以通过这个关于库的广泛讨论,使用C#编写excel。Write to excel using C#

答案 2 :(得分:0)

protected void bt_Express_Click(object sender, EventArgs e)
    {
        string ex = ".xls";
        string FName = "Danh_Sach_Hoc_Sinh";
        FName += ex;
        HtmlForm form = new HtmlForm();
        Literal header = new Literal();
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=" + FName);
        Response.Charset = "UTF-8";
        Response.ContentType = "application/vnd.ms-excel";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        header.Text = "<table><tr><td colspan='6'>Trường: " + Session["TenTruong"].ToString() + "</td><td colspan='2'>Năm học: " + Session["TenNamHoc"].ToString() + "</td></tr> " +
            "<tr><td ALIGN='CENTER' colspan='8'>DANH SÁCH HỌC SINH LỚP.</td></tr>" +
            "<tr><td colspan='8'>" + ((cb_Khoi.SelectedValue == "" && cb_Lop.SelectedValue == "") ? "Toàn trường" : ((cb_Khoi.SelectedValue != "" && cb_Lop.SelectedValue == "") ? "Toàn khối " + cb_Khoi.SelectedValue : "Lớp: " + cb_Lop.SelectedItem.Text + " - Giáo viên: " + db.Rows[0]["GiaoVien"].ToString())) + "</td></tr>" +
            "</table>";

        form.Attributes["runat"] = "server";
        form.Controls.Add(header);
        form.Controls.Add(gv_dshocsinh);
        Controls.Add(form);
        form.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }