导出到Excel

时间:2009-03-30 18:58:01

标签: vb.net excel asp.net-2.0 export-to-excel

我想将GridView导出为ex​​cel,这很容易。但在网格之上,在Excel中,我想要一些其他信息进行识别。我可以以某种方式导出除gridview之外的其他内容,然后将其放入下面的gridview中吗?

修改 出于某种原因,当GridView1可见并且我尝试导出时,整个页面导出而不仅仅是gridview。不知道为什么!

Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
    'Create a StringWriter and HtmlTextWriter
    Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
    Dim htw As New System.Web.UI.HtmlTextWriter(sw)

    'Clear the Response object's content and specify the header for the HTML response and type of application file to create
    Response.ClearContent()
    Response.AddHeader("content-disposition", "attachment; filename=SaveFile.xls")
    Response.ContentType = "application/vnd.ms-excel"
    Response.Charset = ""
    EnableViewState = False

    htw.WriteLine("Test, test, test")

    Try
        'Check for the number of GridView rows
        If GridView1.Rows.Count < 65535 Then
            'Turn sorting and paging off and rebind the GridView control
            GridView1.AllowSorting = False
            GridView1.AllowPaging = False
            GridView1.PageSize = GridView1.Rows.Count
            GridView1.AutoGenerateSelectButton() = False
            GridView1.DataBind()


            'Render the GridView1 as HTML - this will cause an error that will fire the VerifyRenderingInServerForm event -- this event is trapped by the Overriding sub procedure given at the end of the program listing
            GridView1.RenderControl(htw)

            'Write the response
            Response.Write(sw.ToString())
            Response.End()

            'Turn sorting and paging on and rebind the GridView control
            GridView1.AllowSorting = True
            GridView1.AllowPaging = True
            '.GridView1.PageSize = 10
            GridView1.AutoGenerateSelectButton() = True
            GridView1.DataBind()
        End If
    Catch ex As Exception

    End Try

End Sub

5 个答案:

答案 0 :(得分:3)

是的,你可以。

做这样的事情:

HttpContext.Current.Response.Write("some string value")
在您通过gridview之前

答案 1 :(得分:1)

如果您要将内容导出为ExcelML,请查看RadGrid from Telerik

您还可以将标题信息插入网格等

答案 2 :(得分:1)

这是我做同样的代码

protected void ExportExcel_OnClick(object sender, EventArgs e) {
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=brugere.xls");
    Response.Charset = "windows-1252";
    Response.ContentType = "application/vnd.xls";
    using (StringWriter stringWrite = new StringWriter())
    using (HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite)) {
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        GridView1.RenderControl(htmlWrite);
        string html = stringWrite.ToString();
        string result = Replacer.Replace(html, "");
        Response.Write(result);
    }
    Response.End();
}

请注意,我使用正则表达式修剪生成的html,以避免格式化,图像,div和诸如此类的东西。

static readonly Regex Replacer = new Regex("(<input[^<>]*>)|"+
  "(class=\"[^\"]*\")|(style=\"[^\"]*\")|"+
  "(<a[^]*>)|(</a>)|(<div>)|(</div>)|" +
  "(cellspacing=\"[^\"]*\")|(cellpadding=\"[^\"]*\")|" +
  "(id=\"[^\"]*\")|(border=\"[^\"]*\")", RegexOptions.IgnoreCase);

请记住覆盖以下内容以确保网格将在页面外部呈现

public override void VerifyRenderingInServerForm(Control control) {
    return; 
}

答案 3 :(得分:1)

在Excel中打开此文件将生成警告消息。我会使用像NPOI这样的开源导出库之一。 http://npoi.codeplex.com/

如果您仍然喜欢使用HTML输出,可以考虑从此链接下载Office HTML格式的Microsoft文档: http://msdn.microsoft.com/en-us/library/aa155477%28office.10%29.aspx

您只需要此档案中的CHM文件(在EXE中打包)。

祝你好运。

答案 4 :(得分:0)

如果使用DataTable,DataSet或List&lt;&gt;中的数据填充GridView。然后,只需调用一个“ CreateExcelDocument ”函数,就可以将以下库导出到Excel 2007(.xlsx)文件。

// Step 1: Create a DataSet, and put some sample data in it
DataSet ds = CreateSampleData();

// Step 2: Create the Excel .xlsx file
try
{
    string excelFilename = "C:\\Sample.xlsx";
    CreateExcelFile.CreateExcelDocument(ds, excelFilename);
}
catch (Exception ex)
{ 
    MessageBox.Show("Couldn't create Excel file.\r\nException: " + ex.Message);
    return;
}

提供了完整的源代码,因此您可以在一个或多个工作表的顶部对其进行调整,以添加额外的数据行。

该库使用 Open XML 库,因此它完全免费。 http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm