是否可以使用asp.net将sql表导出到excel

时间:2013-08-20 17:24:10

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

我有一个带导出按钮的网页。按下此按钮时是否可以将sql表导出为ex​​cel?我可以使用gridview来完成它,但只需要一个带有代码的简单按钮来完成工作。有人能指出我需要的方向吗?

2 个答案:

答案 0 :(得分:3)

以下是您可以使用的实用程序功能:

Public Shared Sub ExportToSpreadsheet(table As DataTable, filename As String)
    ' Get a hold of the HTTP context and clear it, because we are going to push the CSV data through the context
    Dim context = HttpContext.Current
    context.Response.Clear()

    ' Loop through each column in your data table
    For Each column As DataColumn In table.Columns
        ' Write column names
        context.Response.Write(column.ColumnName + ";")
    Next

    context.Response.Write(Environment.NewLine)

    ' Loop through each row in the data table
    For Each row As DataRow In table.Rows
        ' Loop through each column in row
        For i As Integer = 0 To table.Columns.Count - 1
            ' Write each column value
            context.Response.Write(row(i).ToString().Replace(";", [String].Empty) & ";")
        Next

        ' Write a new line between rows of data
        context.Response.Write(Environment.NewLine)
    Next

    ' Set the content type and headers
    context.Response.ContentType = "text/csv"
    context.Response.AppendHeader("Content-Disposition", "attachment; filename=" & filename & ".csv")
    context.Response.[End]()
End Sub

然后你可以这样称呼它:

ExportToSpreadsheet(YourDataTable, "YourFileName")

注意:由于它是Shared函数,因此您可以将它放在实用程序类中,而不需要实例化(New)类来使用该函数。

答案 1 :(得分:1)

如果你想在excel中使用它,你可以使用以下代码。选择数据并将其放在Gridview中并执行以下操作。

Dim GridView1 As New GridView

SqlDataSource1.SelectCommand = "SELECT * FROM TableName"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()

Response.Clear()
Response.Buffer = True
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)

GridView1.RenderControl(oHtmlTextWriter)

Response.Write(oStringWriter.ToString())
Response.End()

您还可以格式化Gridview,使其在Excel工作表上看起来很好看。