简体   繁体   English

如何将 HTML 表中的数据与选项标签的选定值一起导出到 Excel?

[英]How can you export data in an HTML table to Excel along with the selected value of option tags?

I have a form built with HTML that the user fills out and calculates the total, percentage and rankings of each sections in this form.我有一个用 HTML 构建的表格,用户填写并计算此表格中每个部分的总数、百分比和排名。 I need to export this data into an excel spread sheet.我需要将此数据导出到 excel 电子表格中。 I am able to export it to the spreadsheet but, it is not as neat as I want it to be and also I have option tags and the selected options do not display in the spreadsheet.我可以将它导出到电子表格,但是它不像我想要的那样整洁,而且我有选项标签,并且选定的选项不会显示在电子表格中。

When I click the export to excel both options are displayed but it does not display the selected option which is what I need.当我单击导出到 excel 时,会显示两个选项,但它不会显示我需要的所选选项。 Also, if there is anyway to make this more appealing that would be ideal for me.另外,如果有任何方法可以使这更吸引人,那对我来说是理想的。 Please run my code and I appreciate any code or advice given to me.请运行我的代码,我很感激给我的任何代码或建议。 Thank you.谢谢你。

    <table>
      <tr>
        <th>Category</th>
        <th>Points Possible</th>
        <th>Points Awarded</th>
        <th>Percent Achieved</th>
        <th>Ranking</th>
      </tr>
      <tr>
        <td align="center">A</td>
        <td align="center">60</td>
        <td align="center"><b><div><span id="summary_section_a"></span></div></b></td>
        <td align="center"><b><div><span id="percent_section_a"></span></div></b></td>
        <td bgcolor="#92d050" align="center" id="rank_section_a"></td>
      </tr>
      <tr>
        <td align="center">B</td>
        <td align="center">50</td>
        <td align="center"><b><div><span id="summary_section_b"></span></div></td>
                               <td align="center"><b><div><span id="percent_section_b"></span></div></td>
                               <td bgcolor="#92d050" align="center" id="rank_section_b"></td>
                             </tr>
                             <tr>
                                   <td align="right"><b>Totals=</b></td>
        <td align="center"><b><div></div></b></td>
        <td align="center" id="totalNum"><b></b></td>
        <td align="center"><b><div><span id="TotalPercent"></span></div></b></td>
        <td align="center"></td>

      </tr>
    </table>

    <table>

      <th>Section A.1</th>
      <tr>
        <td>Question 1</td>
        <td align="center"></td>
        <td align="center">
          <select id="a1" class="select section_a" onChange="calcSectionA('section_a')">
            <option value="0">0</option>
            <option value="2">2</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Question 2</td>
        <td align="center"></td>
        <td align="center">
          <select id="a2" class="select section_a" onChange="calcSectionA('section_a')">
            <option value="0">0</option>
            <option value="2">2</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Sub Total</td>
        <td align="center"><b></b></td>
        <td align="center"><b><div id="section_a1subTotal"></div></b></td>
      </tr>
      <th>Section A.2</th>
      <tr>
        <td>Question 1</td>
        <td align="center"></td>
        <td align="center">
          <select id="a3" class="select section_a" onChange="calcSectionA('section_a')">
            <option value="0">0</option>
            <option value="2">2</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Question 2</td>
        <td align="center"></td>
        <td align="center">
          <select id="a4" class="select section_a" onChange="calcSectionA('section_a')">
            <option value="0">0</option>
            <option value="2">2</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Sub Total</td>
        <td align="center"><b></b></td>
        <td align="center"><b><div id="section_a2subTotal"></div></b></td>
      </tr>
      <tr>
        <td class="subtotal">Section A. Total</td>
        <td align="center"><b></b></td>
        <td align="center"><b><div id="total_section_a"></div></b></td>
      </tr>

      <th>Section B.1</th>
      <tr>
        <td>Question 1</td>
        <td align="center"></td>
        <td align="center">
          <select id="b1" class="select section_b" onChange="calcSectionB('section_b')">
            <option value="0">0</option>
            <option value="1">1</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Question 2</td>
        <td align="center"></td>
        <td align="center">
          <select id="b2" class="select section_b" onChange="calcSectionB('section_b')">
            <option value="0">0</option>
            <option value="1">1</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Sub Total</td>
        <td align="center"><b></b></td>
        <td align="center"><b><div id="section_b1subTotal"></div></b></td>
      </tr>
      <th>Section B.2</th>
      <tr>
        <td>Question 1</td>
        <td align="center"></td>
        <td align="center">
          <select id="b3" class="select section_b" onChange="calcSectionB('section_b')">
            <option value="0">0</option>
            <option value="1">1</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Question 2</td>
        <td align="center"></td>
        <td align="center">
          <select id="b4" class="select section_b" onChange="calcSectionB('section_b')">
            <option value="0">0</option>
            <option value="1">1</option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Sub Total</td>
        <td align="center"><b></b></td>
        <td align="center"><b><div id="section_b2subTotal"></div></b></td>
      </tr>
      <tr class="blueHead">
        <td class="subtotal">Section B. Total</td>
        <td align="center"><b></b></td>
        <td align="center"><b><div id="total_section_b"></div></b></td>
      </tr>
    </table>

    <button onclick="exportTableToCSV('MESA.csv')">Export HTML Table To Excel File</button>

    var sections = {
      section_a: 0,
      section_b: 0
    }

    //Calculates Section A
    function calcSectionA(section) {
      let sum = 0;
      //Queries All <Select> and looks for class = "select section_a" and add each selected option and assings it to sum
      document.querySelectorAll('select.' + section)
        .forEach((input) => {
          sum += parseInt(input.options[input.selectedIndex].value);
        });
      sections[section] = sum;
      document.getElementById('total_' + section).textContent = sum;
      document.getElementById('summary_' + section).textContent = sum
      document.getElementById('percent_' + section).textContent = Math.ceil(sum / 8 * 100) + '%';
      calcRanks();
      var a1Q1 = document.getElementById('a1').value;
      var a1Q2 = document.getElementById('a2').value;
      document.getElementById('section_a1subTotal').textContent = parseInt(a1Q1) + parseInt(a1Q2);
      var a2Q1 = document.getElementById('a3').value;
      var a2Q2 = document.getElementById('a4').value;
      document.getElementById('section_a2subTotal').textContent = parseInt(a2Q1) + parseInt(a2Q2);
      var aTotals = document.getElementById('summary_section_a').textContent;
      var bTotals = document.getElementById('summary_section_b').textContent;
      if (aTotals !== "" && bTotals !== "") {
        document.getElementById('totalNum').textContent = parseInt(aTotals) + parseInt(bTotals);
      }
    }

    //Calculates Section B
    function calcSectionB(section) {
      let sum = 0;
      //Queries All <Select> and looks for class = "select section_b" and add each selected option and assings it to sum
      document.querySelectorAll('select.' + section)
        .forEach((input) => {
          sum += parseInt(input.options[input.selectedIndex].value);
        });
      sections[section] = sum;
      document.getElementById('total_' + section).textContent = sum;
      document.getElementById('summary_' + section).textContent = sum
      document.getElementById('percent_' + section).textContent = Math.ceil(sum / 4 * 100) + '%';
      calcRanks();
      var b1Q1 = document.getElementById('b1').value;
      var b1Q2 = document.getElementById('b2').value;
      document.getElementById('section_b1subTotal').textContent = parseInt(b1Q1) + parseInt(b1Q2);
      var b2Q1 = document.getElementById('b3').value;
      var b2Q2 = document.getElementById('b4').value;
      document.getElementById('section_b2subTotal').textContent = parseInt(b2Q1) + parseInt(b2Q2);
      var aTotals = document.getElementById('summary_section_a').textContent;
      var bTotals = document.getElementById('summary_section_b').textContent;
      if (aTotals !== "" && bTotals !== "") {
        document.getElementById('totalNum').textContent = parseInt(aTotals) + parseInt(bTotals);
      }
    }



    function calcRanks() {
      let sectionsArr = [];
      let keys = Object.keys(sections);
      keys.forEach((key, i) => {
        sectionsArr.push({
          section: key,
          value: sections[key],
          rank: 0
        });
        if (i + 1 === keys.length) {
          sectionsArr.sort((a, b) => {
            return a.value > b.value ? -1 : a.value < b.value ? 1 : 0
          });
          let lastIndex = 0;
          for (let i = 1; i < sectionsArr.length; i++) {
            let section = sectionsArr[i];
            let lastSection = sectionsArr[lastIndex];
            //console.log(lastSection.value, section.value);
            if (lastSection.value > section.value) {
              sectionsArr[i].rank = lastSection.rank + 1;
            }
            if (lastSection.value === section.value) {
              sectionsArr[i].rank = lastSection.rank;
            }
            lastIndex = i;
          }
          displayRanks(sectionsArr);
        }
      });
    }

    function displayRanks(sections) {
      sections.forEach((section) => {
        document.getElementById('rank_' + section.section).textContent = section.rank + 1;
      });
    }


    function downloadCSV(csv, filename) {
      var csvFile;
      var downloadLink;

      // CSV file
      csvFile = new Blob([csv], {
        type: "text/csv"
      });

      // Download link
      downloadLink = document.createElement("a");

      // File name
      downloadLink.download = filename;

      // Create a link to the file
      downloadLink.href = window.URL.createObjectURL(csvFile);

      // Hide download link
      downloadLink.style.display = "none";

      // Add the link to DOM
      document.body.appendChild(downloadLink);

      // Click download link
      downloadLink.click();
    }

    function exportTableToCSV(filename) {
      var csv = [];
      var rows = document.querySelectorAll("table tr");

      for (var i = 0; i < rows.length; i++) {
        var row = [],
          cols = rows[i].querySelectorAll("td, th");

        for (var j = 0; j < cols.length; j++)
          row.push(cols[j].innerText);

        csv.push(row.join(","));
      }

      // Download CSV file
      downloadCSV(csv.join("\n"), filename);
    }

Your issue is probably in the line:您的问题可能就在这条线上:

row.push(cols[j].innerText);

Here you are just copying whatever text is inside the cell.在这里,您只是复制单元格内的任何文本。 Instead, you can check for a "select" element inside the cell, and copy the value of that, if available:相反,您可以检查单元格内的“选择”元素,并复制该元素的值(如果有):

const selectElem = cols[j].querySelector('select');
if ( selectElem ) {
    row.push(selectElem.value);
} else {
    row.push(cols[j].innerText);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM