从SQL结果向导出的Excel文件添加自定义列标题名称

时间:2018-02-11 19:39:18

标签: asp.net

我使用以下代码导出到Excel文件。

Protected Sub ExportExcel(sender As Object, e As EventArgs)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand("SELECT date_bs as date_bs,mt_bs as amount,client FROM tbl_p_exp")

            Using sda As New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    Using wb As New XLWorkbook()
                        wb.Worksheets.Add(dt, "Customers")

                        Response.Clear()
                        Response.Buffer = True
                        Response.Charset = ""
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                        Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx")
                        Using MyMemoryStream As New MemoryStream()
                            wb.SaveAs(MyMemoryStream)
                            MyMemoryStream.WriteTo(Response.OutputStream)
                            Response.Flush()
                            Response.End()
                        End Using
                    End Using
                End Using
            End Using
        End Using
    End Using
End Sub

我需要为导出的Excel文件添加特定的列名。

enter image description here

1 个答案:

答案 0 :(得分:0)

正如Alex Kudrayshev在评论中提到的,您可以直接在查询中更改列名。

SELECT column AS [New Column Name]

但是,由于您使用的是DataTables,因此您也可以重命名列。

dt.Columns[0].ColumnName = "New Column Name";