将gridview导出为ex​​cel文件

时间:2011-11-11 13:20:52

标签: asp.net vb.net excel export

我有这个代码 它一直给我错误

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click

    Dim response As HttpResponse = HttpContext.Current.Response()
    response.Clear()
    response.AddHeader("content-disposition", "attachment;filename=XXXXXX.xls")
    response.ContentType = "application/vnd.ms-excel"
    Dim s As System.IO.StringWriter = New System.IO.StringWriter
    Dim htw As HtmlTextWriter = New HtmlTextWriter(s)
    GridView1.RenderControl(htw)
    response.Write(s.ToString)
    response.End()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)

End Sub

错误是在我点击导出后:只能在

期间调用RegisterForEventValidation
Render(); 

并突出显示此脚本

 GridView1.RenderControl(htw)

任何建议

2 个答案:

答案 0 :(得分:1)

在页面级别禁用事件验证:

<%@ Page Language="VB" AutoEventWireup="false" EnableEventValidation="false"  ...

但我会建议creating a real excel file并将该二进制文件写入流而不是HTML表。强烈建议EppPlus easy to use并支持LINQ。 (GPLv2)。

答案 1 :(得分:0)

**复制粘贴以下编码并在添加参考之前测试输出** Microsoft Excel 11.0对象库/ Microsoft Excel 12.0对象库/ Microsoft Excel 14.0对象库

        String fileName ="GVtoExcel";

        Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

        ExcelApp.Application.Workbooks.Add(Type.Missing);
        for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
        {

            ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;

        }
        for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
        {

            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {

                ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();

            }

        }
        ExcelApp.ActiveWorkbook.SaveCopyAs(fileName);

        ExcelApp.ActiveWorkbook.Saved = true;

        ExcelApp.Quit();
       System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);
       ExcelApp = null;