Export Datatable to Excel File (.XLSX)

时间:2021-11-21 16:58:34

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

我使用此代码将Datatable导出到excel文件(.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 "

“Excel无法打开文件'Excel.xlsx',因为文件格式或文件扩展名无效”

I use Excel 2010

我使用Excel 2010

Any Ideas why ?!

任何想法为什么?!

2 个解决方案

#1


1  

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

您正在创建TSV - 制表符分隔值。相反.xlsx尝试使用.tsv

#2


-1  

If you want to export as excel, maybe you can the third-party lib NPOI to make a excel object.

如果要导出为ex​​cel,也许您可​​以使用第三方库NPOI来创建excel对象。

#1


1  

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

您正在创建TSV - 制表符分隔值。相反.xlsx尝试使用.tsv

#2


-1  

If you want to export as excel, maybe you can the third-party lib NPOI to make a excel object.

如果要导出为ex​​cel,也许您可​​以使用第三方库NPOI来创建excel对象。