【问题标题】:Export HTML Table to Excel including Textarea and Dropdown Selected Values将 HTML 表格导出到 Excel,包括 Textarea 和下拉选择值
【发布时间】:2023-03-03 23:12:01
【问题描述】:

我正在尝试将包含下拉列表和注释字段的 HTML 表格保存到 Excel。

我可以很好地保存静态信息,但是评论(文本区域)和下拉列表(选择的值)没有遇到。

<!doctype html>
<head>
<meta charset='utf-8'>

<script>

function fnExcelReport(){
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>"; // bgcolor will give color to your first row
    var textRange; var j=0;
    tab = document.getElementById('tblData'); // id of table

    var table = document.getElementById("tblData");

    for(j = 0 ; j < tab.rows.length ; j++) 
    { 
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
    }

    tab_text=tab_text+"</table>";
    //alert(tab_text);
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Submit.xlsx");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

</script>

</head>

<body>

<table id="tblData">
    <tr>
        <th>Test</th>
        <th>Comments</th>
        <th>Pass or Fail</th>
    </tr>
    <tr>
        <td>Test 1</td>
        <td><textarea rows="2" cols="15" title="Enter comments if necessary" name="comment" placeholder="Comments" form="usrform"></textarea></td>
        <td>
        <select name="cars" autocomplete="off" class="passFail")">                  
                    <option name="default" value="default" selected="selected" disabled="disabled">Pass or Fail</option>
<option value="pass">Pass</option>
<option value="fail">Fail</option>
                    </select>
                    </td>
    </tr>
    <tr>
        <td>Test 2</td>
        <td><textarea rows="2" cols="15" title="Enter comments if necessary" name="comment" placeholder="Comments" form="usrform"></textarea></td>
        <td>
        <select name="cars" autocomplete="off" onchange="java_script_:show(this.options[this.selectedIndex].value)">                    
                    <option name="default" value="default" selected="selected" disabled="disabled">Pass or Fail</option>
<option value="pass">Pass</option>
<option value="fail">Fail</option>
                    </select>
                    </td>
    </tr>
    <tr>
        <td>Test 3</td>
        <td><textarea rows="2" cols="15" title="Enter comments if necessary" name="comment" placeholder="Comments" form="usrform"></textarea></td>
        <td>
            <select name="cars" autocomplete="off" onchange="java_script_:show(this.options[this.selectedIndex].value)">                    
                <option name="default" value="default" selected="selected" disabled="disabled">Pass or Fail</option>
                <option value="pass">Pass</option>
                <option value="fail">Fail</option>
            </select>
        </td>
    </tr>
</table>

<button id="btnExport" onclick="fnExcelReport('headerTable', 'test results');"> EXPORT </button>

</body>
</html>

我正在获取标题行和测试 1、Test2 和 Test3,但是在 cmets 和下拉列表的位置,我实际上在 Excel 中获取了注释字段和下拉列表,而不是在 HTML 中输入的值。

最好是逐个单元格地浏览表格并将其写入 Excel,还是逐列地处理第 2 列和第 3 列不同,因为我不会使用 .innerHTML?

【问题讨论】:

    标签: javascript html excel


    【解决方案1】:

    只需调用函数并将表格 DOM 元素作为参数传递给单击按钮或某些事件,即可以简单的方式使用该代码。在某些情况下,我们不必导出某些列或某些字段,因此我们使用一组自定义的类名,分别识别某些列和输入标签。下面是相同的代码。

    $("#btnExport").click(function(){
          var $table = $("#tblExportGrid");
          ExportHTMLTableToExcel($table);
       });
     function ExportHTMLTableToExcel($table) {
            var tab_text = ""
            var final_text = "";
            var filename = $table.attr('export-excel-filename'); // attribute to be 
            // applied on Table tag
            filename = isNullOrUndefinedWithEmpty(filename) ? "Excel Document" : filename;
            var index = $table.find("tbody tr").length;
            if (Number(index) > 0) {
                $.each($table, function (index, item) {
                    var element = $(item);
                    var headertext = $("#" + element[0].id).closest
                        (":has(label.HeaderLabel)").find('label').text().trim();
                    if (headertext == "") {
                        tab_text = "<table border='2px'><tr>";
                    }
                    else {
                        tab_text = "<table border='2px'><tr> " + headertext + "</tr><tr>";
                    }
    
                    // Create column header
                    element.find("thead tr th").each(function () {
                        if (!$(this).hasClass("NoExport"))
                            tab_text = tab_text + "<td bgcolor='#87AFC6'>" +
                                $(this)[0].innerHTML + "</td>";
                    });
    
                    //Close column header
                    tab_text = tab_text + "</tr>";
    
                    // Create body column
                    element.find(" tbody tr").each(function () {
                        tab_text = tab_text + "<tr>";
                        $(this).find("td").each(function () {
                            if ($(this).hasClass("ExportLabelTD")) {
                                var value = $(this).html();
                                tab_text = tab_text + "<th>" + value + "</th>";
                            }
                            else {
                                $(this).find("input,select").each(function () {
                                    var value = "";
    
                                    if ($(this).prop("type") == 'select-one') {
                                        value = $('option:selected', this).text();
                                    } else {
                                        value = $(this).val();
                                    }
    
                                    if (!$(this).closest("td").hasClass("NoExport") &&
                                        !$(this).hasClass("NoExport")) { // NoExport is used for TD 
                                        // or tan input tag that not needs to be exported
                                        tab_text = tab_text + "<th>" + value + "</th>";
                                    }
                                });
                            }
                        });
                        tab_text = tab_text + "</tr>";
                    });
    
                    // Create colum footer
                    element.find("tfoot tr td").each(function () {
                        var colspan = $(this).attr("colspan");
                        var rowspan = $(this).attr("rowspan");
    
                        colspan = colspan == undefined ? 1 : colspan;
                        rowspan = rowspan == undefined ? 1 : rowspan;
    
                        if ($(this).hasClass("NoExport")) {
                            tab_text = tab_text + "";
                        }
                        else if ($(this).hasClass("ExportValueTD")) // Footer class that needs 
                        // to be no td that have input tags
                        {
                            $(this).find("input,select").each(function () {
                                var value = "";
    
                                if ($(this).prop("type") == 'select-one') {
                                    value = $('option:selected', this).text();
                                } else {
                                    value = $(this).val();
                                }
    
                                if (!$(this).closest("td").hasClass("NoExport") &&
                                    !$(this).hasClass("NoExport")) {
                                    tab_text = tab_text + "<td colspan=" + colspan + "";
                                    rowspan = "" + rowspan + " > " + value + "</th>";
                                }
                            });
                        }
                        else
                            tab_text = tab_text + "<td colspan=" + colspan + ""; 
                        rowspan = "" + rowspan + " > " + $(this).html() + "</td> ";
                    });
    
                    tab_text = tab_text + "<tr></tr></table>";
    
                    if (index == 0) {
                        final_text = tab_text;
                    }
                    else {
                        final_text = final_text + tab_text;
                    }
                });
    
                var ua = window.navigator.userAgent;
                var msie = ua.indexOf("MSIE ");
    
                if (msie > 0 || !!navigator.userAgent.match
                    (/Trident.*rv\:11\./))      // If Internet Explorer
                {
                    txtArea1 = window.open();
                    txtArea1.document.open("txt/html", "replace");
                    txtArea1.document.write(final_text);
                    txtArea1.document.close();
                    txtArea1.focus();
                    sa = txtArea1.document.execCommand("SaveAs", true, filename + ".xls");
                    return (sa);
                }
                else                 //other browser not tested on IE 11
                {
                    //sa = window.open('data:application/vnd.ms-excel,' + 
                    //         encodeURIComponent(final_text));
                    var anchor = document.createElement('a');
                    anchor.setAttribute('href', 'data:application/vnd.ms-excel,' +
                        encodeURIComponent(final_text));
                    anchor.setAttribute('download', filename);
                    anchor.style.display = 'none';
                    document.body.appendChild(anchor);
                    anchor.click();
                    document.body.removeChild(anchor);
                }
            }
        }
    
        function isNullOrUndefinedWithEmpty(text) {
            if (text == undefined)
                return true;
            else if (text == null)
                return true;
            else if (text == null)
                return true;
            else
                false;
        }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <input type="button" id="btnExport" value="Export" />
    <table id="tblExportGrid" export-excel-filename="New Document">
       <thead>
          <th> First Column </th>
          <th> Second Column </th>
          <th class="NoExport"> Third Column </th>
       </thead>
       <tbody>
          <tr>
             <td><input type="text" value="First 1" /></td>
             <td class="ExportLabelTD"> Second 1 </td>
             <td class="NoExport"> Thrid 1 </td>
          </tr>
          <tr>
             <td><input type="text" value="First 2" /></td>
             <td class="ExportLabelTD"> Second 2 </td>
             <td class="NoExport"> Thrid 2 </td>
          </tr>
       </tbody>
       <tfoot>
          <tr>
             <td class="ExportValueTD"><input type="text" value="Foot First 1" /></td>
             <td> Foot Second 1 </td>
             <td class="NoExport"> Foot Thrid 1 </td>
          </tr>
       </tfoot>
    </table>

    【讨论】:

      【解决方案2】:

      我只是逐个单元格地浏览,在我有下拉列表的地方,我只是要求输入文本。

      for (var r = 0, n = table.rows.length; r < n; r++) {
          for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
              if (c == 2 && r > 0) {
              passFail_row = ("passFail" + r);
              var sel = document.getElementById(passFail_row);
              var text= sel.options[sel.selectedIndex].text;
          }
          else 
              alert(table.rows[r].cells[c].innerText);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        • 2018-06-24
        • 2023-03-21
        • 1970-01-01
        相关资源
        最近更新 更多