NPOI 动态生成Excel 转成HTML table显示

直入主题: 

需求:从数据集中出去检索的数据,生成Excel ,转成HTML table 显示在页面上。还可以导出Excel .

我实现的效果图:  

页面---->

Excel---->

 

 

now  ,说下具体的代码:

1、添加组件:

  NPOI 相关组件,Excel转HTML组件。

2、使用了bootstrap 样式,所有要记得引用

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="Script/jQuery-2.1.4.min.js"></script>
    <link href="bootstrap-3.3.5-dist/css/bootstrap.css" rel="stylesheet" />
    <script src="bootstrap-3.3.5-dist/js/bootstrap.js"></script>
    <script src="Script/Main.js"></script>
    <script src="Script/FixTable.js"></script>
    <script src="bootstrap-3.3.5-dist/js/extendPagination.js"></script>
</head>
<body>
    <button class="btn btn-primary" type="button" id="Searchbtn">Search</button>
      <button class="btn btn-primary" type="button" id="Exportbtn">Export</button>
    <div id="reportpan" style="">
        <table id="CountReport" class=" display table-bordered table-hover" style="overflow-x: scroll; white-space: nowrap; text-align: center !important; color: #000000;" cellspacing="0"></table>
        <div style="text-align: right;">
            <div id="CallBackPager"></div>
        </div>
    </div>
</body>
</html>
View Code

3、script  

LoadData(false);
var isref = true;
$(document).ready(function () {
    $("#Searchbtn").click(function () {
        isref = true;
        LoadData(false);
    });
    $("#Exportbtn").click(function () {
        $.dynamicSubmit("GetDataHandler.ashx", { pDistrict: "" });
    });
});
function LoadData(op) {
    var pagesize = 10;
    var pageindex = 1;
    if (op) {
        var cupageindex = $("#CallBackPager li[class='active'] a");
        if (cupageindex.length != 0) {
            pageindex = parseInt(cupageindex[0].innerHTML);
        }
    }
    $.ajax({
        data: { Pindex: pageindex, Psize: pagesize },
        type: "POST",
        url: "GetDataHandler.ashx",
        //  cache: false,
        datatype: "text",
        success: function (data) {

            if (data != "") {
                var ret = data.split("●");
                if (ret.length = 2) {
                    $("#CountReport").html(ret[1] + "<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
                    $("#CountReport tr td ").css("padding", "3");
                    $("#CountReport tr:eq(0)").css("font-size", "14px").css("font-weight", "700");
                    //  $("#CountReport tr:eq(1)").css("font-size", "14px").css("font-weight", "700"); // font-size:14px;font-weight:700
                    var width = $("#reportpan").width;
                    var height = $("#reportpan").height() + 20;
                    FixTable("CountReport", 5, width, height);
                    var totalCount = parseInt(ret[0]);

                    if (isref) {
                        $('#CallBackPager').extendPagination({
                            totalCount: totalCount,
                            showCount: 5,
                            limit: pagesize,
                            callback: function (curr, limit, totalCount) {
                                LoadData(true);
                            }
                        });
                        isref = false;
                    }
                }
            }
        }

    });
}
$.dynamicSubmit = function (url, datas) {

    var form = $('#dynamicForm');

    if (form.length <= 0) {
        form = $("<form>");
        form.attr('id', 'dynamicForm');
        form.attr('style', 'display:none');
        form.attr('target', '');
        form.attr('method', 'post');
        form.attr('enctype', 'multipart/form-data');
        $('body').append(form);
    }

    form = $('#dynamicForm');
    form.attr('action', url);
    form.empty();

    if (datas && typeof (datas) == 'object') {
        for (var item in datas) {
            var $_input = $('<input>');
            $_input.attr('type', 'hidden');
            $_input.attr('name', item);
            $_input.val(datas[item]);

            $_input.appendTo(form);
        }
    }

    form.submit();
}
View Code

4、这里使用了一般处理程序做的实例,so . .. 添加一般处理程序。

  public class GetDataHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string str = context.Request["Psize"];
            CreateExcel createexcel = new CreateExcel();
            if (!string.IsNullOrEmpty(str))
            {
                int psize = Convert.ToInt32(context.Request["Psize"]);
                int pindex = Convert.ToInt32(context.Request["Pindex"]);

                int TotalCount = 0;
                IWorkbook wb = createexcel.GetIWorkbook(psize, pindex, out TotalCount);

                string html = XLSConvertToHtml(wb);
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);
                HtmlNode node = doc.DocumentNode;
                HtmlNode tbody = node.SelectSingleNode("//table/tbody");
                string htmlstring = "";
                if (tbody != null)
                {
                    htmlstring = tbody.InnerHtml;
                }
                context.Response.Write(TotalCount.ToString() + "" + htmlstring);
            }
            else
            {
                int TotalCount = 0;
                IWorkbook wb = createexcel.GetIWorkbook(0, 0, out TotalCount);
                MemoryStream stream = new MemoryStream();
                wb.Write(stream);
                string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
                stream.Seek(0, SeekOrigin.Begin);
                // return File(stream, "application/vnd.ms-excel", "HeadcountByModality" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls");   MVC 中

                context.Response.Clear();
                context.Response.Charset = "GB2312";
                context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息,为"文件下载/另存为"对话框指定默认文件名,  设定编码为UTF8,防止中文文件名出现乱码
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                // 添加头信息,指定文件大小,让浏览器能够显示下载进度
                context.Response.AddHeader("Content-Length", stream.Length.ToString());
                //// 指定返回的是一个不能被客户端读取的流,必须被下载
                // context.Response.ContentType = "application/ms-excel";
                // 把文件流发送到客户端
                context.Response.BinaryWrite(stream.ToArray());
                // 停止页面的执行
                context.Response.End();

            }
        }
        public string XLSConvertToHtml(IWorkbook workbook)
        {
            ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter();

            //set output parameter
            excelToHtmlConverter.OutputColumnHeaders = false;
            excelToHtmlConverter.OutputHiddenColumns = false;
            excelToHtmlConverter.OutputHiddenRows = false;
            excelToHtmlConverter.OutputLeadingSpacesAsNonBreaking = false;
            excelToHtmlConverter.OutputRowNumbers = false;
            excelToHtmlConverter.UseDivsToSpan = false;

            //process the excel file
            excelToHtmlConverter.ProcessWorkbook(workbook);

            //output the html file
            return excelToHtmlConverter.Document.InnerXml;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
View Code

5、为了方便,将一些代码合并到了一个类。

 public class CreateExcel
    {
        public IWorkbook GetIWorkbook(int pagesize, int pagenum, out int TotalCount)
        {
            int Start = (pagenum - 1) * pagesize + 1;
            TotalCount = 0;
            IWorkbook wb = new HSSFWorkbook();
            //创建表  
            ISheet sh = wb.CreateSheet("放射培训及工作证汇总表");
            //  sh.ForceFormulaRecalculation = true;
            int heard = 1;
            #region 设置表头
            IRow row1 = sh.CreateRow(0);

            row1.Height = 20 * 20;

            ICell icell1top = row1.CreateCell(0);
            //  icell1top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell1top.SetCellValue("序号");

            ICell icell2top = row1.CreateCell(1);
            // icell2top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell2top.SetCellValue("大区");

            ICell icelltop = row1.CreateCell(2);
            //  icell2top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icelltop.SetCellValue("城市");

            ICell icell3top = row1.CreateCell(3);
            //  icell3top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell3top.SetCellValue("员工号");

            ICell icell4top = row1.CreateCell(4);
            // icell4top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell4top.SetCellValue("姓名");

            ICell icell5top = row1.CreateCell(5);
            //  icell5top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell5top.SetCellValue("性别");

            ICell icell6top = row1.CreateCell(6);
            //   icell6top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell6top.SetCellValue("身份证号");

            ICell icell7top = row1.CreateCell(7);
            //   icell7top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell7top.SetCellValue("联系方式");

            ICell icell8top = row1.CreateCell(8);
            //  icell8top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell8top.SetCellValue("邮件地址");

            ICell icell9top = row1.CreateCell(9);
            //  icell9top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell9top.SetCellValue("主管经理");

            ICell icell10top = row1.CreateCell(10);
            //  icell10top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell10top.SetCellValue("成本中心");

            ICell icell11top = row1.CreateCell(11);
            //  icell11top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell11top.SetCellValue("产品线");

            ICell icell12top = row1.CreateCell(12);
            //  icell12top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell12top.SetCellValue("岗位");

            ICell icell13top = row1.CreateCell(13);
            //  icell13top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell13top.SetCellValue("在职状态");

            ICell icell14top = row1.CreateCell(14);
            //  icell14top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell14top.SetCellValue("离职时间");

            ICell icell15top = row1.CreateCell(15);
            //  icell15top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell15top.SetCellValue("入职时间");

            ICell icell16top = row1.CreateCell(16);
            //   icell16top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell16top.SetCellValue("岗位转入");

            ICell icell17top = row1.CreateCell(17);
            // icell17top.CellStyle = Getcellstyle(wb, stylexls.默认);
            icell17top.SetCellValue("岗位转出");

            #endregion
            #region 数据
            List<XmlNode> nodelist = GetData(pagesize, pagenum, out TotalCount);

            XmlNode node;
            for (int i = 0; i < nodelist.Count; i++)
            {
                node = nodelist[i];
                IRow irow = sh.CreateRow(i + 1);

                //序号
                ICell icell = irow.CreateCell(0);
                icell.SetCellValue(Start + i);
                //大区
                icell = irow.CreateCell(1);
                icell.SetCellValue(node.SelectSingleNode("District").InnerText);
                //城市
                icell = irow.CreateCell(2);
                icell.SetCellValue(node.SelectSingleNode("City").InnerText);
                //员工号
                icell = irow.CreateCell(3);
                icell.SetCellValue(node.SelectSingleNode("StaffID").InnerText);
                //姓名
                icell = irow.CreateCell(4);
                icell.SetCellValue(node.SelectSingleNode("CName").InnerText);
                //性别
                icell = irow.CreateCell(5);
                icell.SetCellValue(node.SelectSingleNode("Gender").InnerText);
                //身份证号
                icell = irow.CreateCell(6);
                icell.SetCellValue(node.SelectSingleNode("IDNo").InnerText);
                //联系方式
                icell = irow.CreateCell(7);
                icell.SetCellValue(node.SelectSingleNode("Mobile").InnerText);
                //邮件地址
                icell = irow.CreateCell(8);
                icell.SetCellValue(node.SelectSingleNode("Email").InnerText);
                //主管经理
                icell = irow.CreateCell(9);
                icell.SetCellValue(node.SelectSingleNode("LMEmail").InnerText);
                //成本中心
                icell = irow.CreateCell(10);
                icell.SetCellValue(node.SelectSingleNode("CostCenter").InnerText);
                //产品线
                icell = irow.CreateCell(11);
                icell.SetCellValue(node.SelectSingleNode("Modality").InnerText);
                //岗位
                icell = irow.CreateCell(12);
                icell.SetCellValue(node.SelectSingleNode("Position").InnerText);
                //在职状态
                icell = irow.CreateCell(13);
                icell.SetCellValue(node.SelectSingleNode("Status").InnerText);
                //离职时间
                icell = irow.CreateCell(14);
                icell.SetCellValue(node.SelectSingleNode("JoinDate").InnerText);
                //入职时间
                icell = irow.CreateCell(15);
                icell.SetCellValue(node.SelectSingleNode("JoinDate").InnerText);
                //转入岗位
                icell = irow.CreateCell(16);
                icell.SetCellValue(node.SelectSingleNode("Position").InnerText);
                //转出岗位
                icell = irow.CreateCell(17);
                icell.SetCellValue(node.SelectSingleNode("Position").InnerText);

            }
            #endregion
            return wb;
        }

        public List<XmlNode> GetData(int pagesize, int pagenum, out int TotalCount)
        {
            XmlDocument DataXML = GetXML();
            XmlNodeList nodelist = DataXML.SelectNodes("UserList/user");
            TotalCount = nodelist.Count;
            int start = 0;
            int end = 0;
            if (pagesize != 0)
            {
                start = (pagenum - 1) * pagesize;
                end = pagenum * pagesize > TotalCount ? TotalCount : pagenum * pagesize;
            }
            else
            {
                end = TotalCount;
            }
            List<XmlNode> xmlnodelist = new List<XmlNode>();
            for (int i = start; i < end; i++)
            {
                xmlnodelist.Add(nodelist[i]);
            }
            return xmlnodelist;
        }
        public XmlDocument GetXML()
        {
            XmlDocument DataXML = new XmlDocument();
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "User.xml";
            if (File.Exists(filepath))
            {
                DataXML.Load(filepath);
            }
            return DataXML;
        }
    }
View Code

6、特别说明。这个实例是与其他写在一起的,可能有部分代码不需要。这次时间仓促。

 

转载于:https://www.cnblogs.com/LiuFly/p/5075950.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值