asp.netDataTable导出excel方法(2)

上一篇文章提到看到同事导出excel的新方法,感觉比上一篇简单得多,所以想贴上来,与大家分享。

在后台拼数据,都是用的htmltable标签的写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
string line = "text-align:center;border:thin solid windowtext;";//设置单元格格式
StringBuilder content = new StringBuilder();
content.Append("<table class='TableCssWithBorder'><tr>");//拼接一个html的table,把数据都写进table里
content.Append("<td style='" + line + "' rowspan='2'><b>班级</b></td>");
content.Append("<td style='" + line + "' colspan='2'><b>英语四级</b></td>");
content.Append("<td style='" + line + "' colspan='2'><b>英语六级</b></td>");
content.Append("<td style='" + line + "' colspan='2'><b>总计</b></td></tr>\n");//标题
for (int j = 0; j < dt.Rows.Count; j++)//添加数据,dt.Rows是datatable中的
{
    content.Append("<tr>");
    content.Append("<td style='text-align:center;" + line + "'>" + dt.Rows[j]["Classes"] + "</td></tr>");//主要是格式,数据这些仅供参考。
    
    }   
content.Append("</table>");
string url = @"/UserReportFile/全部统计表/" + Guid.NewGuid().ToString() + "/";//url
try
{
    string fileSavePath = context.Server.MapPath(url);
    Directory.CreateDirectory(fileSavePath);
    File.WriteAllText(fileSavePath + "sum.xls", content.ToString(), Encoding.UTF8);//写到文件里
    context.Response.Write(url + "全部报名统计表.xls");//生成!
}
catch
{
    context.Response.Write("error");
}

前端的写法是

1
2
if (data.indexOf("xls") >= 0) {
                            window.open("http://" + window.location.host + data);//用的传递数据的方法是ajax,对返回过来的数据进行判断,这样就能下载你导出的excel了

  真的很简单!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值