0

这是代码。但是 Excel 文件显示的是整个 aspx 页面而不是 gridview。

Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
    Try

        Response.Clear()
        Response.AddHeader("content-disposition", ("attachment;filename=HotelList_" & DateTime.Now.Year.ToString().Trim()) + DateTime.Now.Month.ToString().Trim().PadLeft(2, Convert.ToChar("0")) + DateTime.Now.Day.ToString().Trim().PadLeft(2, Convert.ToChar("0")) & ".xls")
        Response.Charset = ""
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Response.ContentType = "application/vnd.ms-excel"

        Dim stringWrite As New System.IO.StringWriter
        Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)

        Dim selctedCountry As String = ddlCountry.SelectedItem.Text.ToString()
        Dim selCity As String = ddlCity.SelectedItem.Text.ToString()

        htmlWrite.Write("<div style='PADDING-RIGHT: 5px; PADDING-LEFT: 5px; PADDING-BOTTOM: 0px; PADDING-TOP: 0px'><h3>HOTEL LIST</h3>")
        htmlWrite.Write("<table><tr><td colspan='2'> Country  : " & selctedCountry & " </td></tr>")
        htmlWrite.Write("<table><tr><td colspan='2'> City     : " & selCity & " </td></tr>")

        gvHotelMarkup.RenderControl(htmlWrite)
        htmlWrite.Write("</div>")

        Response.Write(stringWrite.ToString())
        Response.End()


    Catch ex As Exception
        lblErrMessage.Message = ex.Message()
    End Try

End Sub

知道如何解决这个问题吗?提前致谢。

4

2 回答 2

0

下载 ClosedXML 库

using ClosedXML.Excel;   
using System.IO;
using System.Data;

Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click

DataTable dt = new DataTable("GridView_Data");
foreach(TableCell cell in GridView1.HeaderRow.Cells)
{
    dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
    dt.Rows.Add();
    for (int i=0; i<row.Cells.Count; i++)
    {
        dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
    }
}
using (XLWorkbook wb = new XLWorkbook())
{
    wb.Worksheets.Add(dt);

    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
    using (MemoryStream MyMemoryStream = new MemoryStream())
    {
        wb.SaveAs(MyMemoryStream);
        MyMemoryStream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.End();
    }
}
于 2013-10-11T01:45:53.430 回答
0

I'm not sure what exactly the problem is but when I added this to codebehind it worked perfect

  Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        ' Confirms that an HtmlForm control is rendered for the specified ASP.NET
        '               server control at run time. 

    End Sub
于 2013-10-10T09:58:05.647 回答