DataTable导出到Excel、GSV (转)
在程序开发中经常会遇到大量数据的操作问题,有的时候还是少不了Excel,GSV等,需要进行数据文件类型的备份。
当然可以在数据端可以操作。右点击数据库->任务->导出数据->数据源选择应该导出的格式。下一步就可以编写SQL语句获得自己想要的数据啦,但是这个需要操作数据库,而真正的系统开发中,能够直接操作数据库的人很少。所以这种方法只能作为管理做临时查询时使用。
在开发过程中,特别是进行查询统计的时候,需要将一些数据报表,导出到Excel或者其它的存储格式,用于打印、文档分析、提交报告等。这就要求我们在程序开发的时候进行处理,提供接口供用户导出数据。下面就简单介绍几种将数据导出到Excel的方法。
<1>将数据导出,存储在服务器,然后提供链接用于用户下载,其特点:
-
结果可以持久保存,用户可以下载历史版本
-
占用服务器空间
-
依赖控件属性
具体的逻辑代码如下:
protected void Button2_Click(object sender, EventArgs e)
{
DataTable thisTable = AddTimeBusiness.getInstance().GetTable();
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid excel = new DataGrid();
excel.DataSource = thisTable.DefaultView;
//绑定到DataGrid
excel.DataBind();
excel.RenderControl(htmlWriter);
//这里指定文件的路径
string filestr = "d:\\data\\" + "11.xls";
int pos = filestr.LastIndexOf("\\");
string file = filestr.Substring(0, pos);
if (!Directory.Exists(file))
{
Directory.CreateDirectory(file);
}
System.IO.StreamWriter sw = new StreamWriter(filestr);
sw.Write(stringWriter.ToString());
sw.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
DataTable thisTable = AddTimeBusiness.getInstance().GetTable();
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid excel = new DataGrid();
excel.DataSource = thisTable.DefaultView;
//绑定到DataGrid
excel.DataBind();
excel.RenderControl(htmlWriter);
//这里指定文件的路径
string filestr = "d:\\data\\" + "11.xls";
int pos = filestr.LastIndexOf("\\");
string file = filestr.Substring(0, pos);
if (!Directory.Exists(file))
{
Directory.CreateDirectory(file);
}
System.IO.StreamWriter sw = new StreamWriter(filestr);
sw.Write(stringWriter.ToString());
sw.Close();
}
<2>当用户导出时,直接将数据导出客户端,几种方法,感觉此类方法比较适用。
其特点:随时生成,在服务器没有保存副本,方便、快捷。
具体的逻辑代码如下面小例子:
导出到Excel
//根据需要得到数据表
DataTable thisTable = getTable(condition.ToString());
if (thisTable != null)
{
StringWriter sw = new StringWriter();
sw.WriteLine("编号\t帐号\t姓名\t电话\t地址\t金额\t开通时间");
foreach (DataRow dr in thisTable.Rows)
{
sw.WriteLine(dr["F_ID"] + "\t" + dr["F_Psnid"] + "\t" + dr["F_Name"] + "\t" + dr["F_Tel"]
+ "\t" + dr["F_Address"] + "\t" + dr["F_TradeMoney"] + "\t" + dr["F_TradeTime"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=YinHeUserInfo.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();
}
导出到Excel
//根据需要得到数据表
DataTable thisTable = getTable(condition.ToString());
if (thisTable != null)
{
StringWriter sw = new StringWriter();
sw.WriteLine("编号\t帐号\t姓名\t电话\t地址\t金额\t开通时间");
foreach (DataRow dr in thisTable.Rows)
{
sw.WriteLine(dr["F_ID"] + "\t" + dr["F_Psnid"] + "\t" + dr["F_Name"] + "\t" + dr["F_Tel"]
+ "\t" + dr["F_Address"] + "\t" + dr["F_TradeMoney"] + "\t" + dr["F_TradeTime"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=YinHeUserInfo.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();
}
补充:如果需要导出为GSV文件,只需要上例分隔符“\t”用“,”替换就可以了。
<3>即可下载到客户端,又能够在服务器保存副本。可以说,此方法满足了以上的两种方法的功能。
如果你只想将结果保存在服务器端,则此种方法比第一种方法更加合理,不用过分的依赖控件的属性。其实这就是一种文件流的操作。所以第一种方法不可取。
Code
string filePath = "d:\\data.xls";//这个你可以自己修改为虚拟路径
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine("编号\t帐号\t姓名\t电话\t地址\t金额\t开通时间");
foreach (DataRow dr in thisTable.Rows)
{
sw.WriteLine(dr["F_ID"] + "\t" + dr["F_Psnid"] + "\t" + dr["F_Name"] + "\t" + dr["F_Tel"]
+ "\t" + dr["F_Address"] + "\t" + dr["F_TradeMoney"] + "\t" + dr["F_TradeTime"]);
}
sw.Close();
fs.Close();
#region==如果要下载到客户端,则添加下列代码==
//Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filePath));
//Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
//Response.WriteFile(filePath); // 把文件流发送到客户端
//Response.End();
#endregion
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
this.Repeater1.RenderControl(hw);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
Page.EnableViewState = false;
Response.AppendHeader("Content-Disposition", "attachment;filename=Teacher.xls");
Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=GB2312\"><title> Copyright by SDU</title></head><body><center>");
Response.Write(sw.ToString());
Response.Write("</center></body></html>");
Response.End();
说明:当字符型的数字串导出到excel的时候,经常自动变为科学记数法表示,解决的方法,绑定到Repeater1的时候如此:
<td style="vnd.ms-excel.numberformat:@"><%# DataBinder.Eval(Container.DataItem, "shenfenzheng") %></td>
Code
string filePath = "d:\\data.xls";//这个你可以自己修改为虚拟路径
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine("编号\t帐号\t姓名\t电话\t地址\t金额\t开通时间");
foreach (DataRow dr in thisTable.Rows)
{
sw.WriteLine(dr["F_ID"] + "\t" + dr["F_Psnid"] + "\t" + dr["F_Name"] + "\t" + dr["F_Tel"]
+ "\t" + dr["F_Address"] + "\t" + dr["F_TradeMoney"] + "\t" + dr["F_TradeTime"]);
}
sw.Close();
fs.Close();
#region==如果要下载到客户端,则添加下列代码==
//Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filePath));
//Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
//Response.WriteFile(filePath); // 把文件流发送到客户端
//Response.End();
#endregion
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
this.Repeater1.RenderControl(hw);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
Page.EnableViewState = false;
Response.AppendHeader("Content-Disposition", "attachment;filename=Teacher.xls");
Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=GB2312\"><title> Copyright by SDU</title></head><body><center>");
Response.Write(sw.ToString());
Response.Write("</center></body></html>");
Response.End();
说明:当字符型的数字串导出到excel的时候,经常自动变为科学记数法表示,解决的方法,绑定到Repeater1的时候如此:
<td style="vnd.ms-excel.numberformat:@"><%# DataBinder.Eval(Container.DataItem, "shenfenzheng") %></td>