I am trying to convert the data that is in a GridView to either Excel or a CSV file. Ultimately, the data is going to be imported into Microsoft Access. Essentially, it doesn't matter how this is done, as long as the data is legible, correct and able to be imported into an Access database.
I have tried the code below, and it does work. But when I try to load the data into excel or import the data into Access I get the following error message:
"The file you are trying to open is in a different format than specified by the extension."
Also, if you open the file in notepad, the data is in HTML format, not CSV.
Any help in getting the data from the gridview into either Excel, CSV or Access would be greatly appreciated!
Private Sub ExportToExcel(ByVal strFileName As String, ByVal dg As GridView) Response.Clear() Response.Buffer = True Response.ContentType = "application/vnd.ms-excel" Response.AddHeader("content-disposition", "attachment;filename=" & strFileName) Response.Charset = "" Me.EnableViewState = False Dim oStringWriter As New System.IO.StringWriter Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter) gvHistory.RenderControl(oHtmlTextWriter) Response.Write(oStringWriter.ToString()) Response.[End]() End Sub Protected Sub btnCSV_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCSV.Click ExportToExcel("Report.xls", gvHistory) End Sub