前些時間有朋友為了完成此功能,就硬把數據導入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中兩列之間的分隔符號