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>

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();
}

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;
            }
        }
    }

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;
        }
    }

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

时间: 2024-08-05 08:03:08

NPOI 动态生成Excel 转成HTML table显示的相关文章

npoi根据html字符串动态生成excel模板

npoi多表头数据导出目前有两种方法: 其一是根据excel模板来导出数据 其二是npoi动态创建多表头 上面的两种方法我都用过今天我介绍的是根据html字符串来创建excel,但是要设置响应的属性, 其实也就是对应 npoi CellRangeAddress 方法所需要的四个参数(firstrow,lastrow,firstcol,lastcol),这四个参数代表的意思是 单元格的开始行索引,结束行索引,开始列索引,结束列索引. 先要有table表头的字符串然后用HtmlAgilityPack

MVC4+EF5+Oracle项目点滴记录(001)将数据库中的数据用NPOI导出生成excel

关于NOPI 2.0在项目中的使用 1.在官网下载 NPOI 文件包 http://npoi.codeplex.com/releases 下载后将NPOI.dll和ICSharpCode.SharpZipLib.dll加载到项目中  最好是全部加载(NPOI.OOXML.dll.NPOI.OpenXml4Net.dll.NPOI.OpenXmlFormats.dll) 2.在三层中的Model层中新建一个类,专门用来处理数据表导成Excel,这里先导出数据库City表中的全部信息 代码如下 (注

动态生成web表-asp.net table

1. 页面上定义一个server 的table <table style="width: 100%" id="tbContent" runat="server"> </table>   2. 后台 HtmlTableRow rowQy = new HtmlTableRow(); HtmlTableCell cellHeadQty = new HtmlTableCell(); cellHeadQty.Width = &quo

JAVAWEB 生成excel文字在一格显示两位不变成#号

在处理excel的时候会发现这种问题,如果是人家给的模板还好,如果不是模板的话, 就需要进行处理了,一个小单元格,如果是一位的话,如1-9显示没有问题,一旦是两位的话, 显示的10就变成了# 结果方法是在数字前面加上 上引号 “ ’ ”就能变成文本单元格的形式就能显示正常,

DataGridView绑定DataTable动态生成列 并且将列名中文显示

方法一: DataGridView绑定获取到的DataTable数据,然后根据每一列手动设置列名,如图 方法二: 在写SQL查询语句的时候,直接在select后边的字段上 AS 想要显示的中文名称即可;如图

MVC +NPOI+AJAX 查询并生成excel 下载

Controller 代码: public class SubArea2STIReportController : BaseController { [ActionDescription("分区2STI查询")] public ActionResult Index() { var vm = CreateVM<SubArea2STIReportVM>(); return PartialView(vm); } [HttpPost] [ActionDescription(&quo

数据库与Excel报表的动态生成

一.数据库与Excel报表的动态生成 (1)读取数据库的数据动态生成Excel报表,这是JSP应用中常遇到的问题,本节采用的基本方法是: 在Excel工作薄中,将报表模板制作在第一张工作表中,从数据库中读取数据,利用POI组件复制模板工作表 而得到一张新的工作表,将查询数据填写到新的工作表中. (2) 实例分析 写一个Servlet程序,查询pubs数据库的titles表和sales表,把查询结果集数据填写到图6-14的报表中, 操作步骤如下: 第1步:新建一个名类为"DBExcelServle

动态生成随机背景色表格

<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>动态生成随机背景色表格</title> <style> table{margin-top:20px;width:800px;border:1px solid #ddd;border-collapse:collapse;} td{border:1px solid #ddd;padding:

关于动态生成dom绑定事件失效的原因

之前做项目都是直接用jquery的bind绑定事件,不过当时都不是动态生成dom元素,而是已经页面中原本存在的dom元素进行事件绑定,最近在测试给动态生成的dom绑定事件的时候发现事件失效,于是就测试了一下: 1.事件失效的原因:(1)bind事件绑定只对dom中存在的元素有效,对于我们后来动态增加的元素是监测不到,所以绑定不了 (2)同样,当你使用var aa = document.getElementsByTagName("动态生成的元素");来获取动态生成的元素的时候也是获取不到