适合使用的场合:
.net 中从前台中的table导出成excel文件,兼容各种浏览器。
使用工具:
org.in2bits.MyXls.dll
从前台获取表格的thead和表格的tbody,将其转化为字符串,用逗号隔开
html:
<div class="printContent"> <table cellspacing="1" class="tablesorter table-04"> <thead> <tr><th>校友会编号</th><th>校友会名称</th><th>常设办事处</th><th>主席姓名</th><th>联系电话</th><th>建会时间</th><th>总人数</th><th>依托学院</th></tr> </thead> <tfoot> <tr><th>校友会编号</th><th>校友会名称</th><th>常设办事处</th><th>主席姓名</th><th>联系电话</th><th>建会时间</th><th>总人数</th><th>依托学院</th></tr> </tfoot> <tbody> @foreach (var l in Model) { <tr id="@(l.XYHBH)"><td>@(l.XYHBH)</td><td>@(l.XYHMC)</td><td>@(l.BGSDZ)</td><td>@(l.XYHZX)</td><td>@(l.LXDH)</td><td>@(DAL.IsNull.ShortDateNull(l.CJSJ.ToString()))</td><td>@(l.HYZS)</td><td>@(BLL.ZYGLMK.XX_YXSJBQK.GetYXMC(l.YXSH))</td></tr> } </tbody> </table></div>
javascript:
var heads = ""; var bodys = ""; var i = 0; //获取title内容,每一空以,隔开 $(".printContent table thead tr th").each(function () { heads = heads + $(this).text() + ","; i++; }); i = 0; //获取tbody内容,每一空以,隔开 $(".printContent table tbody tr td").each(function () { bodys = bodys + $(this).text() + ","; i++; }); //发送请求,传表格内容 $.post("/Shared/ExportExcel", { head: heads, body: bodys }, function (data) { //创建表格成功,保存在服务器 if (data == "1") { //访问服务器指定文件,下载表格 window.location.href = "/Shared/DownLoadExcel"; } });
引用
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using org.in2bits.MyXls;
ExportExcel:
//导出excel文件 #region 导出Excel public int ExportExcel(string head, string body) { //将字符串拆分成数组,获取每一个单元格内容 string[] heads = head.Split(','); string[] bodys = body.Split(','); XlsDocument xls = new XlsDocument(); //文件名称 xls.FileName = "excel.xls"; //excel作者 xls.SummaryInformation.Author = Session["UID"].ToString().Trim(); //主题 xls.SummaryInformation.Subject = "LIIP&A"; //公司 xls.DocumentSummaryInformation.Company = "Intelligent Information Processing and Application Lab"; int len = heads.Length - 1; //excel中sheet名称 string sheetName = Session["UID"].ToString().Trim(); int colCount = len;//总列数 int rowCount = bodys.Length / len;//总行数 Worksheet sheet = xls.Workbook.Worksheets.AddNamed(sheetName); Cells cells = sheet.Cells; int t = 0; //生成excel表格内容,从第0行到len-1行 for (int r = 0; r <= rowCount; r++) { //第一行(title) if (r == 0) { for (int c = 0; c < colCount; c++) { //在一行内创建colCount个单元格,第1+r行第1+c列的值为heads[c] cells.Add(1 + r, 1 + c, heads[c]). Font.Bold = true;//字体加粗 } } else //表示正文 { for (int c = 0; c < colCount; c++) { cells.Add(1+r,1+c,bodys[t]); t++; } } } //保存到服务器 xls.Save(Server.MapPath("/Content"),true); return 1; } //文件下载 public FileResult DownLoadExcel() { return File(Server.MapPath("/Content/excel.xls"), "application/ms-excel","excel.xls"); }