JavaScript写导出Excel和打印

基本可以满足对复杂的表格进行导出成Excel的需求,但是导出的Excel文件会提示格式错误,不影响查看内容。目前处于小白阶段,只能先实现满足需求,后期会继续完善。

方便日后查看,完整代码如下:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>XXX检查工作记录</title>
    <link href="resources/css/origin/style.css" rel="stylesheet" type="text/css"/>
    <link href="resources/css/print/normalize.min.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="resources/js/origin/jquery.js"></script>
    <script type="text/javascript">
        var idTmr;

        function getExplorer() {
            var explorer = window.navigator.userAgent;
            //ie
            if (explorer.indexOf("MSIE") >= 0) {
                return 'ie';
            } else if (window.ActiveXObject || "ActiveXObject" in window) {
                return 'ie11';
            }
            //firefox
            else if (explorer.indexOf("Firefox") >= 0) {
                return 'Firefox';
            }
            //Chrome
            else if (explorer.indexOf("Chrome") >= 0) {
                return 'Chrome';
            }
            //Opera
            else if (explorer.indexOf("Opera") >= 0) {
                return 'Opera';
            }
            //Safari
            else if (explorer.indexOf("Safari") >= 0) {
                return 'Safari';
            }
        }

        function exportExcel(tableid) {
            alert("下载")
            console.info(getExplorer())
            if (getExplorer() == 'ie') {
                try {
                    var curTbl = document.getElementById(tableid);
                    //创建AX对象excel
                    var oXL = new ActiveXObject("Excel.Application");
                    //获取workbook对象
                    var oWB = oXL.Workbooks.Add();
                    //获取在workbook中读取第一个sheet
                    var xlsheet = oWB.Worksheets(1);
                    //创建TextRange
                    var sel = document.body.createTextRange();
                    //把表格中的内容移到TextRange中
                    sel.moveToElementText(curTbl);
                    //选中数据
                    sel.select();
                    //模拟复制
                    sel.execCommand("Copy");
                    //模拟粘贴
                    xlsheet.Paste();
                    //打开 excel界面
                    oXL.Visible = true;
                    var fname = oXL.Application.GetSaveAsFilename("Excel", "Excel Spreadsheets (*.xlsx)");

                } catch (e) {
                    dialogAlert("提示: 须允许ActiveX控件运行才能导出Excel文件!\n\n或<br>如果您确信您的电脑中已经安装了Excel," + "那么请调整IE的安全级别。\n\n具体操作:\n\n" + "工具 → Internet选项 → 安全 → 自定义级别 → 对没有标记为安全的ActiveX进行初始化和脚本运行 → 启用",
                        '', function () {
                            var form = document.forms[0];
                            form.action = location.href + '?timestamp=' + new Date().getTime();
                            form.submit();
                            console.log(location.href);
                        });
                    return false;
                } finally {
                    oWB.SaveAs(fname);
                    oWB.Close(savechanges = true);
                    oXL.Quit();
                    idTmr = window.setInterval("Cleanup();", 1);
                }
            } else if (getExplorer() == 'ie11') {
                try {
                    var doc = document.getElementById(tableid);
                    //创建excel类型的Application
                    var exl = new ActiveXObject("Excel.Application");
                    //不显示界面
                    exl.visible = false;
                    var wbook = exl.Workbooks.Add();
                    var sheet = wbook.Worksheets(1);
                    //创建TextRange
                    var sel = document.body.createTextRange();
                    sel.moveToElementText(doc);
                    //选中数据
                    // sel.select();
                    //模拟复制
                    sel.execCommand("Copy");
                    //模拟粘贴
                    sheet.Paste();
                    //打开 excel界面
                    exl.Visible = true;
                    var fname = exl.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
                } catch (e) {
                    dialogAlert("提示: 须允许ActiveX控件运行才能导出Excel文件!\n\n或<br>如果您确信您的电脑中已经安装了Excel," + "那么请调整IE的安全级别。\n\n具体操作:\n\n" + "工具 → Internet选项 → 安全 → 自定义级别 → 对没有标记为安全的ActiveX进行初始化和脚本运行 → 启用",
                        '', function () {
                            var form = document.forms[0];
                            form.action = location.href + '?timestamp=' + new Date().getTime();
                            form.submit();
                            console.log(location.href);
                        });
                    return false;
                }
                wbook.SaveAs(fname);
                wbook.Close(false);
                exl.Quit();
                idTmr = window.setInterval("Cleanup()", 1);
            } else {
                console.info("进入else" + tableid)
                tableToExcel(tableid)
            }
        }

        function Cleanup() {
            window.clearInterval(idTmr);
            CollectGarbage();
        }

        var tableToExcel = (function () {
            var uri = 'data:application/vnd.ms-excel;base64,',
                template = '<html><head><meta charset="UTF-8"><style>h4 {text-align: center;font-size: 2.2em;font-weight: normal;margin: 5px 0px 15px 0px;}' +
                    'td{line-height: 4em;padding: 5px;font-size: 1.8em}</style></head><body><table>{table}</table></body></html>',
                base64 = function (s) {
                    return window.btoa(unescape(encodeURIComponent(s)))
                },
                format = function (s, c) {
                    return s.replace(/{(\w+)}/g,
                        function (m, p) {
                            return c[p];
                        })
                }
            return function (table, name) {
                $("td").css({'border': '2px solid black', 'text-align': 'center'});
                $("#tableTitle td").css({'border': '0px', 'text-align': 'center'});
                $("#serialNo td").css({'border': '0px', 'text-align': 'right'});

                if (!table.nodeType) table = document.getElementById(table)
                $('.hide').html($(table).clone());
                var $cloneTable = $(".hide table");
                $cloneTable.find("input,textarea").each(function () {
                    // $(this).parent().text($(this).parent().text() + $(this).val());//遍历文本输入框中的值,并拼接父节点的文字
                    $(this).parent().text($(this).val());//遍历文本输入框中的值
                })
                var ctx = {worksheet: name || 'Worksheet', table: $cloneTable.html()}

                window.location.href = uri + base64(format(template, ctx));
                // $("table table td").css({'border': '0px'})
                // $("#tfoot td").css({'border': '0px'});

            }
        })()

        function plxj() {
            alert("打印")
            $("#ele5").print({
                //Use Global styles
                globalStyles: true,
                //Add link with attrbute media=print
                mediaPrint: false,
                //Custom stylesheet
                stylesheet: "http://fonts.googleapis.com/css?family=Inconsolata",
                //Print in a hidden iframe
                iframe: false,
                //Don't print this  选择不打印的class
                noPrintSelector: ".avoid-this",

                //Add this on bottom
                append: "<br/>Buh Bye!",
                //Log to console when printing is done via a deffered callback
                deferred: $.Deferred().done(function () {
                    console.log('Printing done', arguments);
                })
            });
        }

        $(function () {
            loadData();
        })

        function loadData() {
            var recordId = localStorage["recordId"];//接收列表页面存储的id值
            $.ajax({
                url: "inspectionrecord/getTableInfo.action",
                type: "post",
                data: {
                    id: recordId
                },
                success: function (data) {
                    if (data.code == "200") {
                        var i = data.data.id;
                        if (i < 10) {
                            $("#nowId").html("000000" + data.data.id);
                        } else if (i > 9 && i < 100) {
                            $("#nowId").html("00000" + data.data.id);
                        } else if (i > 100 && i < 1000) {
                            $("#nowId").html("0000" + data.data.id);
                        } else if (i > 1000 && i < 10000) {
                            $("#nowId").html("000" + data.data.id);
                        }
                        $("#inspectiontime").val(data.data.inspectiontime);
                        $("#inspectedunit").val(data.data.inspectedunit);
                        $("#inspector").val(data.data.inspector);
                        $("#checktheunit").val(data.data.checktheunit);
                        document.getElementById("checkcontent").value=data.data.checkcontent;
                        // document.getElementById("checkcontent").innerText = data.data.checkcontent;
                        document.getElementById("inspectthesituation").value = data.data.inspectthesituation;
                        // document.getElementById("inspectthesituation").innerText = data.data.inspectthesituation;
                        document.getElementById("inspectionrequirements").value = data.data.inspectionrequirements;
                        // document.getElementById("inspectionrequirements").innerText = data.data.inspectionrequirements;
                        $("#inspectedunitsigned").val(data.data.inspectedunitsigned);
                    }
                }
            })
        }

        function saveRecord() {
            // alert("修改后保存"+localStorage["recordId"])
            $.ajax({
                url: "inspectionrecord/editRecord..action",
                type: "post",
                data: {
                    id: localStorage["recordId"],
                    Inspectiontime: $("#inspectiontime").val().trim(),
                    Inspectedunit: $("#inspectedunit").val().trim(),
                    inspector: $("#inspector").val().trim(),
                    Checktheunit: $("#checktheunit").val().trim(),
                    checkcontent: $("#checkcontent").val().trim(),
                    inspectthesituation: $("#inspectthesituation").val().trim(),
                    inspectionrequirements: $("#inspectionrequirements").val().trim(),
                    Inspectedunitsigned: $("#inspectedunitsigned").val().trim(),
                    state:localStorage["recordState"]
                },
                success: function (data) {
                    if (data.code == "200") {
                        alert(data.description);
                        loadData();
                    } else {
                        alert(data.description)
                        loadData();
                    }
                },
                error: function () {
                    alert("error")
                }
            })
        }
    </script>
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script>
        window.jQuery || document.write('<script src="resources/js/print/jquery.min.js"><\/script>')
    </script>
    <script src="resources/js/print/jQuery.print.js"></script>
</head>

<body>
<div class="place">
    <span>位置:</span>
    <ul class="placeul">
        <li><a href="index.html">首页</a></li>
        <li><a href="inspectionrecord.html">三品一标</a></li>
    </ul>
</div>

<div class="tools">

    <ul class="toolbar">

        <li class="click" onclick="exportExcel('test')"></span>导出成Excel</li>
        <li class="click1" onclick="plxj()">打 印</li>
        <li class="click1" onclick="saveRecord()">保存</li>
    </ul>
    <div class="hide" id="hide" style="display:none;">
    </div>
</div>

<div class="tabL" id="ele5">

    <!--<b id="nowId">0004751</b>-->
    <table width="100%" border="0" cellspacing="0" cellpadding="0" id="test">
        <tr id="serialNo">
            <td colspan="4" id="nowId"></td>
        </tr>
        <tr id="tableTitle">
            <td colspan="4"><h4>xxx检查工作记录</h4></td>
        </tr>
        <tr>
            <td>检查时间</td>
            <td><input type="text" id="inspectiontime"/></td>
            <td>被检单位</td>
            <td><input type="text" id="inspectedunit"/></td>
        </tr>
        <tr>
            <td>检查人员</td>
            <td><input type="text" id="inspector"/></td>
            <td>检查单位</td>
            <td><input type="text" id="checktheunit"/></td>
        </tr>
        <tr>
            <td>检查内容</td>
            <td colspan="3"><textarea name="textarea3" rows="5" id="checkcontent"></textarea></td>
        </tr>
        <tr>
            <td>检查情况</td>
            <td colspan="3"><textarea name="textarea" rows="5" id="inspectthesituation"></textarea></td>
        </tr>
        <tr>
            <td>检查要求</td>
            <td colspan="3"><textarea name="textarea2" rows="5" id="inspectionrequirements"></textarea></td>
        </tr>
        <tr>
            <td>被检单位人员签字</td>
            <td colspan="3"><input type="text" id="inspectedunitsigned"/></td>
        </tr>
    </table>
    <p align="right" style="font-size:0.7em; margin-top:10px;">XXX委员会(印制)</p>
</div>
</body>
<style type="text/css">
    * {
        padding: 0px;
        margin: 0px;
        font-family: 微软雅黑, 黑体
    }

    b {
        color: #666;
        font-size: 1em;
        display: block;
        width: 100%;
        text-align: right;
    }

    h4 {
        text-align: center;
        font-size: 2.0em;
        font-weight: normal;
        margin: 5px 0px 15px 0px;
    }

    table {
        /*border-right: 1px solid #222;*/
        /*border-bottom: 1px solid #222;*/
        font-size: 14px;
        color: #000;
    }

    td {
        border: 2px solid #222;
        line-height: 20px;
        text-align: center;
        padding: 5px;
        font-size: 1.4em;
        color: #000;
    }

    input[type="text"],
    textarea {
        border: 0px;
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        font-size: 0.9em;
        color: #000;
    }

    table table,
    table table td {
        border: 0px;
    }

    table table td {
        text-align: left;
        line-height: normal;
    }

    table table td input[type="text"] {
        width: auto;
    }

    .no td {
        padding: 5px;
        line-height: normal;
    }

    .fl {
        float: left;
    }

    .fr {
        float: right;
    }

    .fl input,
    .fr input {
        width: auto;
    }

    input[type="text"].data {
        text-align: right;
    }

    input[type="text"].text {
        border-bottom: 1px solid #000;
    }

    #nowId {
        border: 0px solid white;
        text-align: right;
        color: #ff201e;
    }

    #tableTitle td {
        border: 0px solid white;
    }

</style>
</html>

@彭彭
写于2018年9月14日15:34:52

猜你喜欢

转载自blog.csdn.net/qq_31839039/article/details/82703705