导出excel-文件流
后台代码(控制器或者dao层)
public void Excel(){
//第一步:(1)以虚拟表的形式获取导出数据
DataTable dt_0 = this.service.Excel();
//第一步:(2)若字段复杂新建虚拟表并设置栏位(调整字段顺序或者渲染字段)
DataTable dt_1 = new DataTable();
DataColumn field = null;
field = new DataColumn("标题一"); dt_1.Columns.Add(field);
//第一步:(3)构建字典,用于字段的渲染
Dictionary<string, string> dic= new Dictionary<string, string>();
if(dic.ContainsKey("键")){//true
dic.Add("键","值");
}
//第一步:(4)遍历dt_0,处理数据插入dt_1
foreach (DataRow row in dt_0.Rows){
DataRow dataRow_1 = dt_1.NewRow();
if (row.ItemArray[3] != null) {
if (dic.ContainsKey(row.ItemArray[3].ToString())){
dataRow_1[0] = dic[row.ItemArray[3].ToString()];
}
}
dt_1.Rows.Add(dataRow_1);
}
//第二步:整理excel栏位数据
List<string> exceltitle_0 = new List<string>();
exceltitle_0 .Add("标题一");
exceltitle_0 .Add("标题二");
exceltitle_0 .Add("标题三");
exceltitle_0 .Add("标题四");
exceltitle_0 .Add("标题五");
//第三步:用stringbuilder画excel
StringBuilder sHtml = new StringBuilder();
sHtml.Append("<meta http-equiv='content-type' content='application/ms-excel; charset=UTF-8'/>");
sHtml.Append("<table border=1>");
//第四步:(1)画excel栏位
sHtml.Append("<tr style='background-color:#D8DFF1;'>");
var i = 0;
foreach (String s in tabletitle_0){
if(i == 0){
sHtml.Append("<td rowspan='2'>");
sHtml.Append(s);
sHtml.Append("</td>");
i++;
}else if( i == 1){
sHtml.Append("<td colspan='2' ");
sHtml.Append(s);
sHtml.Append("</td>");
i++;
}else if(i == 2){
sHtml.Append("<td rowspan='2'>");
sHtml.Append(s);
sHtml.Append("</td>");
sHtml.Append("</tr>");
i++;
}else if(i == 3){
sHtml.Append("<tr style='background-color:#D8DFF1;'>");
sHtml.Append("<td>");
sHtml.Append(s);
sHtml.Append("</td>");
i++;
}else{
sHtml.Append("<td>");
sHtml.Append(s);
sHtml.Append("</td>");
sHtml.Append("</tr>");
}
}
//第五步:(1)画excel数据单元格
foreach (DataRow row in dt_1.Rows){
sHtml.Append("<tr>");
foreach (object cell in row.ItemArray){
sHtml.Append("<td>");
sHtml.Append(cell);
sHtml.Append("</td>");
}
sHtml.Append("</tr>");
}
sHtml.Append("</table>");
//第六步:定义流
System.Web.HttpContext.Current.Response.Charset = "GB2312";
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddhhmmsss")+ ".xls", System.Text.Encoding.UTF8).ToString());
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
System.Web.HttpContext.Current.Response.Output.Write(sHtml);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}