将asp GridView导出为CSV格式时,html代码将与gridview一起打印

时间:2019-03-05 19:25:43

标签: c# asp.net excel csv gridview

尝试将asp Gridview导出为CSV。 它工作正常,但也可以打印出整个html代码。

这是我的代码段以及输出的外观。

 protected void btn1_Click(object sender, EventArgs e)
        {

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=newSample.csv");

            Response.ContentType = "application/excel";
            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

            GridView1.RenderControl(htmlTextWriter);
            Response.Write(stringWriter.ToString());
            Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {

        }

我在输出中得到的是:

<div>
    <table cellspacing="0" rules="all" border="1" id="GridView1" style="border-collapse:collapse;">
        <tr>
            <th scope="col">Animal</th><th scope="col">Code</th><th scope="col">Age</th>
        </tr><tr>
            <td></td><td></td><td></td>
        </tr><tr>
            <td>Dog </td><td>123456</td><td>2</td>
        </tr><tr>
            <td>Cat </td><td>234567</td><td>6</td><td>
        </tr><tr>
            <td>Deer </td><td>345678</td><td>24</td><td>
        </tr><tr>
            <td>Tiger </td><td>456789</td><td>8</td><td>
        </tr><tr>
            <td>Lion</td><td>567891</td><td>7</td><td>
        </tr>
    </table>
</div>

我应该得到的是:

    Animal,Code,Age
    Dog,123456,2
    Cat,234567,6
    Deer,345678,24
    Tiger,456789,8
    Lion,567891,7

我该如何实现?有什么我想念的吗?

0 个答案:

没有答案