asp.net Linq把数据导出到Excel的代码
更新时间:2008年10月13日 23:37:24 作者:
最近有需要通过WEB把数据导出到Excel的功能, 关于导出数据到Excel并无什么新奇可言,网络上到处都是,但基本上都是一种模式,通过DataGrid 把数据导出到Excel的方式。
前些时间有朋友为了完成此功能,就硬把数据导入DataGrid再导出到Excel。这实在是多此一举。
解决办法:
通过Linq将数据读出,并直接写入数据流中
代码如下:
public partial class DataToExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataAccess.DataClassesDataContext db = new DataClassesDataContext();
var qu = from t in db.TXLInfos
select t;
Response.AppendHeader("Content-Disposition", "attachment;filename=result.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "gb2312";
Response.ContentEncoding = Encoding.GetEncoding("gb2312");
System.IO.StringWriter writer = new System.IO.StringWriter();
foreach(TXLInfo item in qu)
{
writer.Write(item.GQName);
writer.Write("\t");
writer.Write(item.GQID);
writer.WriteLine();
}
Response.Write(writer.ToString());
Response.End();
}
}
注:"\t"默认做为Excel中两列之间的分隔符号
解决办法:
通过Linq将数据读出,并直接写入数据流中
代码如下:
复制代码 代码如下:
public partial class DataToExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataAccess.DataClassesDataContext db = new DataClassesDataContext();
var qu = from t in db.TXLInfos
select t;
Response.AppendHeader("Content-Disposition", "attachment;filename=result.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "gb2312";
Response.ContentEncoding = Encoding.GetEncoding("gb2312");
System.IO.StringWriter writer = new System.IO.StringWriter();
foreach(TXLInfo item in qu)
{
writer.Write(item.GQName);
writer.Write("\t");
writer.Write(item.GQID);
writer.WriteLine();
}
Response.Write(writer.ToString());
Response.End();
}
}
相关文章
asp.net 数据绑定 使用eval 时候报 字符文本中的字符太多 问题的解决方法
asp.net 数据绑定 使用eval 时候报 字符文本中的字符太多 问题解决,需要的朋友可以参考下。2010-09-09


最新评论