asp.net导出数据到execl并保存到本地 不需要调用Office组件

2016-12-30 09:57:24来源:oschina作者:深圳大道人点击

第七城市
public static string ExportTable(DataSet ds)
{
StringBuilder sb = new StringBuilder();
int count = 0;
foreach (DataTable tb in ds.Tables)
{
sb.AppendLine("");
sb.AppendLine("");
//写出列名,样式随便定义
sb.AppendLine("");
foreach (DataColumn column in tb.Columns)
{
if (column.ColumnName == "标题" || column.ColumnName == "链接")
sb.AppendLine("");
else
sb.AppendLine("");
}
sb.AppendLine("");
//写出数据
foreach (DataRow row in tb.Rows)
{
sb.Append("");
foreach (DataColumn column in tb.Columns)
{
sb.Append("");
}
sb.AppendLine("");
count++;
}
sb.AppendLine("
" + column.ColumnName + "" + column.ColumnName + "
" + row[column].ToString() + "
");
}
return sb.ToString();
} //调用
protected void btnSaveWord_Click(object sender, EventArgs e)
{
System.Web.UI.Page page = this.Page;
page.Response.Clear();
page.Response.Buffer = true;
page.Response.Charset = "gbk";
string name = tname.Text + System.DateTime.Now.ToString("_yyMMdd_hhmm") + ".xls";
page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + name);
page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");//设置输出流为简体中文
page.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
page.EnableViewState = false;
//我这个是根据页面选择的数据导出
string[] id = Request.Form["ck"].ToString().Split(',');
good = new DAL.GoodMessage();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("标题", typeof(string));
dt.Columns.Add("链接", typeof(string));
dt.Columns.Add("来自", typeof(string));
foreach (string idstr in id)
{
foreach (DataRow dr in good.GetDataById(Convert.ToInt32(idstr)).Tables[0].Rows)
{
DataRow dr1 = dt.NewRow();
dr1["标题"] = dr["title"];
dr1["链接"] = dr["url"];
dr1["来自"] = dr["froms"];
dt.Rows.Add(dr1);
}
}
ds.Tables.Add(dt);
page.Response.Write(ExportTable(ds));
page.Response.End();
Response.Redirect("DownloadWord.aspx?id=" + name);
} //下载页面
protected void Page_Load(object sender, EventArgs e)
{
string FullFileName = Request.QueryString["id"];
// 需要转换为绝对路径,否则会自动认到C盘系统里那个IIS目录下面去,而且,无法通过URI的方式来进行数据流读取。如果你生成的文件不在web目录下,也需要明确指出。

FileInfo DownloadFile = new FileInfo(HostingEnvironment.ApplicationPhysicalPath + FullFileName);
// 下面到就是读取文件,通过数据流的方式下载了。
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FullFileName, System.Text.Encoding.UTF8));
Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
Response.WriteFile(DownloadFile.FullName);
Response.Flush();
Response.End();
}
第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台