我正在开发一个应用程序,我希望我在datagrid视图中为用户显示数据集。现在用户想要以excel格式下载datagridview中的数据。我该怎么办?
1)我应该在excel中写入数据集并在用户下载文件之前将其保存到服务器中吗?
2)我可以使用超链接并将服务器中保存的文件路径设置为超链接hRef属性,以便用户可以单击并下载文件吗?
我正在使用C#ASP.net 2.0
请帮忙!
答案 0 :(得分:1)
无需将文件保存到服务器使用以下代码,将动态创建文件:
Public Shared Sub DataTableToExcel(ByVal dt As DataTable, ByVal FileName As String
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Write(Environment.NewLine)
For Each row As DataRow In dt.Rows
For i As Integer = 0 To dt.Columns.Count - 1
HttpContext.Current.Response.Write(row(i).ToString().Replace(";", String.Empty) + ";")
Next
HttpContext.Current.Response.Write(Environment.NewLine)
Next
HttpContext.Current.Response.ContentType = "application/ms-excel"
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls")
HttpContext.Current.Response.[End]()
End Sub
答案 1 :(得分:1)
您可以使用这个简单的代码来完成
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=SummaryReport" + DateTime.Now.ToString() + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
grd.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
答案 2 :(得分:1)