过完年回来之后,被公司派到了另外一个地方上班,这几天一直在做excel导出的工作,看着以前大神编的代码学到不少,他们用的导出excel的方法很棒,所以想贴上来,与大家分享。
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"); }
前段的写法是
if (data.indexOf("xls") >= 0) { window.open("http://" + window.location.host + data);//用的传递数据的方法是ajax,对返回过来的数据进行判断,这样就能下载你导出的excel了
asp.netdatatable导出excel方法--不用a标签实现
原文:http://www.cnblogs.com/junshijie/p/5275171.html