要下载的网格视图数据? [英] grid view data to be downloaded ?
本文介绍了要下载的网格视图数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的网站上,我有一个网格视图,其中显示了一些公司数据.我想提供一种功能,允许将网格视图中显示的数据下载到excel工作表或其他内容上.请帮助
in my website i have a grid view which displays some company data . I want to provide a functionality that allows to download the data displayed in grid view onto to a excel sheet or something .Please help
推荐答案
最简单的方法是重新运行用于填充网格的查询并创建数据的CSV版本,可以使用Response.Write和
发送该数据
The easiest way to do it is to rerun the query used to populate the grid and create a CSV version of the data, which can be sent using Response.Write and
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName));
Response.ContentType = "application/vnd.xls";
搜索"asp.net Excel CSV"应该带您一些代码示例.
注意:如果数据类型是Excel将错误地"格式化的数据类型,则将CSV发送到Excel可能会出现问题.例如,像2545551234这样的电话号码将以指数形式显示.
A search for "asp.net Excel CSV" should bring you to some code examples.
Note: sending a CSV to Excel can have problems if the datatypes are some of the ones Excel will format "incorrectly". For example, a phone number like 2545551234 will show up in exponential notation.
此示例可能会为您提供帮助,
[] 将 GridView导出到Excel [ ^ ]
:)
This example might help you,
[ ]Export GridView to Excel[^]
:)
public void ExportToExcel(SqlDataSource dataSrc, string fileName)
{
//Add Response header
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
//GET Data From Database
SqlConnection cn = new SqlConnection(dataSrc.ConnectionString);
string query = dataSrc.SelectCommand.Replace("\r\n", " ").Replace("\t", " ");
SqlCommand cmd = new SqlCommand(query, cn);
cmd.CommandTimeout = 999999 ;
cmd.CommandType = CommandType.Text;
try
{
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
//Add Header
for (int count = 0; count < dr.FieldCount; count++)
{
if (dr.GetName(count) != null)
sb.Append(dr.GetName(count));
if (count < dr.FieldCount - 1)
{
sb.Append(",");
}
}
Response.Write(sb.ToString() + "\n");
Response.Flush();
//Append Data
while (dr.Read())
{
sb = new StringBuilder();
for (int col = 0; col < dr.FieldCount - 1; col++)
{
if (!dr.IsDBNull(col))
sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append(",");
}
if (!dr.IsDBNull(dr.FieldCount - 1))
sb.Append(dr.GetValue(dr.FieldCount - 1).ToString().Replace(",", " "));
Response.Write(sb.ToString() + "\n");
Response.Flush();
}
dr.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cmd.Connection.Close();
cn.Close();
}
Response.End();
}
这篇关于要下载的网格视图数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文