简体   繁体   中英

Export Datatable to Excel File (.XLSX)

I use this code to export Datatable to excel file (.xlsx)

Dim attachment As String = "attachment; filename=Excel.xlsx"
    Response.ClearContent()
    Response.AddHeader("content-disposition", attachment)
    Response.ContentType = "application/vnd.ms-excel"
    Dim tab As String = ""
    For Each dc As DataColumn In dt.Columns
        Response.Write(tab + dc.ColumnName)
        tab = vbTab
    Next
    Response.Write(vbLf)

    Dim i As Integer
    For Each dr As DataRow In dt.Rows
        tab = ""
        For i = 0 To dt.Columns.Count - 1
            Response.Write(tab & dr(i).ToString())
            tab = vbTab
        Next
        Response.Write(vbLf)
    Next
    Response.End()

When I download the file I get This message :

"Excel cannot open the file 'Excel.xlsx' because the file format or file extension is not valid "

I use Excel 2010

Any Ideas why ?!

Your are creating a TSV - tab separated value. Instead .xlsx try using .tsv

如果要导出为ex​​cel,也许可以通过第三方lib NPOI来制作excel对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM