2014-02-26 14 views
0

想知道是否有人可以給我答案和一些提示,如果它可能將grindview導出到.xlsx(2007版本的Excel中)。Gridview to .xlsx

我已經設法將grindview轉移到.xls(2003 excel),但不能轉移到xlsx。

我的代碼是:

問候 Lime3003

Protected Sub ExportToExcel(sender As Object, e As EventArgs) 
        Response.Clear() 
    Response.Buffer = True 
    Response.AddHeader("content-disposition", "attachment;filename=" + selReportName + " .xls") 
    Response.Charset = "" 
    Response.ContentType = "Application/vnd.openxmlformats - officedocument.spreadsheetml.sheet" 
    'Response.ContentType = "application/vnd.ms-excel" 

    Using sw As New StringWriter() 
     Dim hw As New HtmlTextWriter(sw) 

     gwResult.GridLines = GridLines.Both 
     gwResult.RenderControl(hw) 
     'style to format numbers to string 
     Dim style As String = "<style> .textmode { } </style>" 
     Response.Write(style) 
     Response.Output.Write(sw.ToString()) 
     Response.Flush() 
     Response.[End]() 
    End Using 
End Sub 

Public Overrides Sub VerifyRenderingInServerForm(control As Control) 
    ' Verifies that the control is rendered 
End Sub 
+1

您正在創建一個html表格,然後將這個html文本保存爲一個excel文件。你不能把它轉換成一個真正的excel文件。爲此,我建議[EPPlus](http://epplus.codeplex.com/wikipage?title=WebapplicationExample)。 –

回答

0

蒂姆Schmelter說我是用EPPlus出口數據視圖,但我需要將其更改爲數據表。

Protected Sub ExportToExcel(sender As Object, e As EventArgs) 

    Dim dt As DataTable 

    dt = dvData.ToTable 

    'MsgBox(gwResult.HeaderRow.Cells.Count) 
    Try 
     Dim pck = New OfficeOpenXml.ExcelPackage() 
     Dim ws = pck.Workbook.Worksheets.Add(selReportName) 
     ws.Cells("A2").LoadFromDataTable(dt, True) 

     Response.Clear() 
     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 
     Response.AddHeader("content-disposition", "attachment; filename=" + selReportName + ".xlsx") 
     Response.BinaryWrite(pck.GetAsByteArray()) 
     'log error 
    Catch ex As Exception 
    End Try 
    Response.[End]() 

End Sub