我有一个使用各种输入创建的数据表。有时,生成的表格为35000多行。目前,数据表显示在gridview上。它在几分钟后装好。然后,可以选择将gridview导出到excel文件。每次我们有一个要导出的大表时,转换都会失败。
我的目标是绕过gridview步骤并获取格式化表并将其直接放入excel文件中。也可以是csv文件,如果写入/加载更快,只要数据表类似于gridview输出。
我在这里尝试了以下代码Export DataTable to Excel File。我尽力将它转换为vb,这里......
Protected Sub btnExportData_Click(sender As Object, e As EventArgs) Handles btnExportData.Click
Dim dt As DataTable
dt = CreateDataSource()
Dim filename As String = "attachment; filename=DistComplain.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", filename)
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 = ""
i = 0
Do While (i < dt.Columns.Count)
Response.Write((tab + dr(i).ToString))
tab = "" & vbTab
i = (i + 1)
Loop
Response.Write("" & vbLf)
Next
Response.End()
End Sub
CreateDataSource()是在内存中创建的表。然后是调用它来填充gridview的其他按钮。现在它成功遵守并运行,然后成功创建文件。虽然,当文件尝试打开时,我收到此错误...
Excel Error http://i48.tinypic.com/6y3bkk.png
当我尝试xls和csv文件时会发生这种情况。有些东西没有得到正确的翻译。任何解决方案?
答案 0 :(得分:1)
(在Google的帮助下撰写)使用StringWriter class:
创建导出Public Shared Sub ExportDataSetToExcel(ds As DataSet, filename As String)
Dim response As HttpResponse = HttpContext.Current.Response
'Clean response object
response.Clear()
response.Charset = ""
'Set response header
response.ContentType = "application/vnd.ms-excel"
response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & """")
'Create StringWriter and use to create CSV
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
'Instantiate DataGrid
Dim dg As New DataGrid()
dg.DataSource = ds.Tables(0)
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
response.[End]()
End Using
End Using
End Sub
您只需要传递DataSet和文件名的功能。如果您不想编辑CreateDataSource()
函数,可以先将其合并到DataSet中,如下所示:
Dim dt As DataTable = CreateDataSource()
Dim ds As New DataSet
ds.Merge(dt)
答案 1 :(得分:0)
您的问题是关于您收到无法打开文件的消息的原因,对吗?
根据Microsoft的说法,当您启用“忽略使用动态数据交换(DDE)的其他应用程序”设置时会发生这种情况。 (见here)。该链接包含更改设置的说明。