How do I save a datagrid to excel in vb.net?

2020-07-30 04:24发布

I know that this should be easy but how do I export/save a DataGridView to excel?

标签: vb.net excel
9条回答
爷、活的狠高调
2楼-- · 2020-07-30 04:55

You could use crystal since it is built into VS. Predefine a crystal report with the appropriate columns and then you can use any datasource you would use for a datagrid or gridview.

 Dim report_source As CrystalDecisions.Web.CrystalReportSource
 report_source.ReportDocument.SetDataSource(dt) 'DT IS A DATATABLE
 report_source.Report.FileName = "test.rpt"
 report_source.ReportDocument.Refresh()
 report_source.ReportDocument.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.Excel, "c:\test.xls")
查看更多
Melony?
3楼-- · 2020-07-30 04:56

You can use this library for more detailed formatting
http://www.carlosag.net/Tools/ExcelXmlWriter/

There are samples in the page.

查看更多
来,给爷笑一个
4楼-- · 2020-07-30 04:58

I setup the gridview and then used the html text writer object to spit it out to a .xls file, like so:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'get the select command of the gridview
    sqlGridview.SelectCommand = Session("strSql")
    gvCompaniesExport.DataBind()
    lblTemp.Text = Session("strSql")

    'do the export
    doExport()

    'close the window
    Dim closeScript As String = "<script language='javascript'> window.close() </scri"
    closeScript = closeScript & "pt>"
    'split the ending script tag across a concatenate to keep it from causing problems
    'this will write it to the asp.net page and fire it off, closing the window
    Page.RegisterStartupScript("closeScript", closeScript)
End Sub
Public Sub doExport()
    Response.AddHeader("content-disposition", "attachment;filename=IndianaCompanies.xls")
    Response.ContentType = "application/vnd.ms-excel"
    Response.Charset = ""
    Me.EnableViewState = False
    Dim objStrWriter As New System.IO.StringWriter
    Dim objHtmlTextWriter As New System.Web.UI.HtmlTextWriter(objStrWriter)
    'Get the gridview HTML from the control
    gvCompaniesExport.RenderControl(objHtmlTextWriter)
    'writes the dg info
    Response.Write(objStrWriter.ToString())
    Response.End()
End Sub
查看更多
登录 后发表回答