您的位置:首页 > 编程语言 > ASP

ASP.NET 导出Excel快捷的方法(不使用组件)

2013-11-22 10:30 597 查看
/// <summary>

///

/// </summary>

/// <param name="ds">数据源</param>

/// <param name="FileName">文件名称</param>

/// <param name="names">列头集合</param>

/// <param name="fields">列名集合</param>

/// <param name="title">报表头</param>

/// <param name="foot">报表尾</param>

/// <param name="fileURL">返回的报表相对路径</param>

private void bbCreateExcel(DataSet ds,string FileName, string[] names, string[] fields, string title, string foot,ref string fileURL)

{

DataTable dt = ds.Tables[0];

try

{

System.Text.StringBuilder sb = new System.Text.StringBuilder();

sb.Append("<table border=1>");

//构造标题

if (!string.IsNullOrEmpty(title))

{

sb.Append("<tr>");

sb.Append(string.Format("<td colspan=" + fields.Length+ " style=" + "text-align:center;font-weight:bold" + string.Format(">{0}<br/><br></td>", title)));

sb.Append("</tr>");

}

//构造列头

sb.Append("<tr>");

foreach (string name in names)

{

sb.Append(string.Format("<td style="+"text-align:center;font-weight:bold"+string.Format(">{0}</td>",name)));

}

sb.Append("</tr>");

//填值

for (int i = 0; i < dt.Rows.Count; i++)

{

sb.Append("<tr>");

foreach(string columnName in fields)

{

sb.Append("<td>" + dt.Rows[i][columnName].ToString() + "</td>");

}

sb.Append("</tr>");

}

//构造报表底部

if (!string.IsNullOrEmpty(foot))

{

sb.Append("<tr>");

sb.Append(string.Format("<td colspan=" + fields.Length+" style=" + "text-align:right;font-weight:bold" + string.Format(">{0}<br><br></td>", foot)));

sb.Append("</tr>");

}

sb.Append("</table>");

//如果保存excel的文件夹不存在创建文件夹

if (!Directory.Exists(Server.MapPath("../../excel")))

{

Directory.CreateDirectory(Server.MapPath("../../excel"));

}

//文件路径

string strFileName=FileName + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";

string serverPath = Server.MapPath("../../excel") + "\\" + strFileName;

//保存文档到指定路径

StreamWriter sr = new StreamWriter(serverPath, false, System.Text.Encoding.UTF8);

sr.WriteLine(sb.ToString());

sr.Close();

//返回路径转换为相对路径

fileURL = "excel/" + strFileName;

// // 输入出临时文件到客户端

System.IO.FileInfo file = new System.IO.FileInfo(serverPath);

Response.Clear();

Response.Charset = "GB2312";

Response.ContentEncoding = System.Text.Encoding.Default;

// 添加头信息,为"文件下载/另存为"对话框指定默认文件名

Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(strFileName));

// 添加头信息,指定文件大小,让浏览器能够显示下载进度

Response.AddHeader("Content-Length", file.Length.ToString());

// 指定返回的是一个不能被客户端读取的流,必须被下载

Response.ContentType = "application/ms-excel";

// 把文件流发送到客户端

Response.WriteFile(file.FullName);

// 停止页面的执行

//file.Delete();

Response.Flush();

// Response.End();

HttpContext.Current.ApplicationInstance.CompleteRequest();

}

catch(Exception ex)

{

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: