0

エクスポート ボタンのある Web ページがあります。このボタンを押すと、SQL テーブルを Excel にエクスポートできますか? 私は gridview でそれを行うことができますが、作業を行うにはコードビハインドを含む単純なボタンが必要です。誰かが私が必要な方向に私を向けることができますか?

4

2 に答える 2

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、関数を使用するためにクラスをインスタンス化 ( ) する必要はありません。

于 2013-08-20T17:37:47.127 に答える
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 シートで見栄えを良くすることもできます。

于 2013-08-20T17:57:06.717 に答える