0

下面是我用来将我的 gridview 数据导出到 Excel 的方法。用户询问我是否可以命名工作表选项卡。有任何想法吗?提前致谢!

Private Sub btnExportToExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportToExcel.Click        
    Dim form As New HtmlForm
    Dim strAttachment As String
    Dim stw As StringWriter
    Dim htextw As HtmlTextWriter

        stw = New StringWriter
        strAttachment = "attachment; filename=" & strAppName & ".xls"
        HttpContext.Current.Response.ClearContent()
        HttpContext.Current.Response.AddHeader("content-disposition", strAttachment)
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
        htextw = New HtmlTextWriter(stw)
        form.Controls.Add(CType(Session("gridViewControl"), Control))
        Me.Controls.Add(form)
        form.RenderControl(htextw)
        Response.Write("<b>" & txtTitle.Text & "</b><br />")
        Response.Write(stw.ToString())            
        Response.Flush()
        Response.Close()
        HttpContext.Current.ApplicationInstance.CompleteRequest()

End Sub
4

3 回答 3

1

Its not possible because your output is really HTML with an HTML Table - which Excel will happily "parse"/translate into rows and columns (because that's what a table is). You're not really creating a "native" Excel file.

You can have more options (assuming all your clients do have Excel) by using Excel XML using native .Net (LINQ to XML, don't be scared by that term). I believe Excel XML support goes back to Office 2003 (maybe even Office XP/2002, but I could be wrong).

You can do so in C# or VB.net, but in VB.net it's almost trivial because of VB.Net's XML literals. See this MSDN video by Beth Massi for inspiration (magic starts around 5:00, but the entire video is worth every minute).

于 2012-04-25T15:14:17.273 回答
0

你不能通过 html 来做,但你可以通过 xml (SpreadsheetML) 来做。看看我在此处的答案中发布的示例:
在 ASP.NET 中生成 Excel 文件

于 2012-04-25T18:55:07.203 回答
0

不,没有办法使用这种方法来做到这一点。您必须使用像Gembox这样的专门库来执行此操作。

于 2012-04-25T14:55:56.267 回答