如何使用javascript将html表导出为ex​​cel

时间:2011-07-04 02:31:01

标签: javascript html

我的表格式为

<table id="mytable">
<thead>
  <tr>
    <th>name</th>
    <th>place</th>
  </tr>
</thead>
<tbody>
<tr>
   <td>adfas</td>
   <td>asdfasf</td>
</tr>
</tbody>
</table>

我在网上找到了以下代码。但如果我使用“thead”和“tbody”标签

,它就不起作用
function write_to_excel() {

    str = "";

    var mytable = document.getElementsByTagName("table")[0];
    var rowCount = mytable.rows.length;
    var colCount = mytable.getElementsByTagName("tr")[0].getElementsByTagName("td").length;

    var ExcelApp = new ActiveXObject("Excel.Application");
    var ExcelSheet = new ActiveXObject("Excel.Sheet");
    ExcelSheet.Application.Visible = true;

    for (var i = 0; i < rowCount; i++) {
        for (var j = 0; j < colCount; j++) {
            str = mytable.getElementsByTagName("tr")[i].getElementsByTagName("td")[j].innerHTML;
            ExcelSheet.ActiveSheet.Cells(i + 1, j + 1).Value = str;
        }
    }

10 个答案:

答案 0 :(得分:10)

仅适用于Mozilla,Chrome和Safari ..

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.0.js">            </script>
<script type="text/javascript">
$(function(){
    $('button').click(function(){
        var url='data:application/vnd.ms-excel,' + encodeURIComponent($('#tableWrap').html()) 
        location.href=url
        return false
    })
})
</script>
<style type="text/css">

</style>
<title>Untitled</title>
    </head>
    <body>
    <button>click me</button>
    <div id="tableWrap">
    <table>
    <thead>
    <tr><th>A</th><th>B</th><th>C</th></tr>
    </thead>
    <tbody>
    <tr><td>1</td><td>2</td><td>3</td></tr>
    <tr><td>1</td><td>2</td><td>3</td></tr>
    <tr><td>1</td><td>2</td><td>3</td></tr>
    <tr><td>1</td><td>2</td><td>3</td></tr>
    </tbody>
    </table>
    </div>
    </body>
  </html>

答案 1 :(得分:7)

您在互联网上找到的解决方案无法正常工作的原因是因为线路启动var colCount。变量mytable只有两个元素<thead><tbody>var colCount行正在查找mytable<tr>的所有元素。您可以做的最好的事情是为您的<thead><tbody>提供一个ID,然后根据该ID获取所有值。假设你有<thead id='headers'>

function write_headers_to_excel() 
{
  str="";

  var myTableHead = document.getElementById('headers');
  var rowCount = myTableHead.rows.length;
  var colCount = myTableHead.getElementsByTagName("tr")[0].getElementsByTagName("th").length; 

var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;

for(var i=0; i<rowCount; i++) 
{   
    for(var j=0; j<colCount; j++) 
    {           
        str= myTableHead.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
        ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
    }
}

}

然后对<tbody>标记执行相同的操作。

编辑:我也强烈建议使用jQuery。它会将此缩短为:

function write_to_excel() 
{
 var ExcelApp = new ActiveXObject("Excel.Application");
 var ExcelSheet = new ActiveXObject("Excel.Sheet");
 ExcelSheet.Application.Visible = true; 

  $('th, td').each(function(i){
    ExcelSheet.ActiveSheet.Cells(i+1,i+1).Value = this.innerHTML;
  });
}

现在,当然,这会给你一些格式问题,但你可以弄清楚你希望它在Excel格式化的方式。

编辑:要回答有关如何为n个表执行此操作的问题,jQuery将会执行此操作。要在原始Javascript中执行此操作,请获取所有表,然后更改函数以便能够将表作为参数传递。例如:

var tables = document.getElementsByTagName('table');
for(var i = 0; i < tables.length; i++)
{
  write_headers_to_excel(tables[i]);
  write_bodies_to_excel(tables[i]);
}

然后将function write_headers_to_excel()更改为function write_headers_to_excel(table)。然后将var myTableHead = document.getElementById('headers');更改为var myTableHead = table.getElementsByTagName('thead')[0];。与您的write_bodies_to_excel()相同,或者您想要设置它。

答案 2 :(得分:5)

这可能是从this question复制的更好答案。请尝试一下,在这里发表意见。如果发现有用,请投票。谢谢。

<script type="text/javascript">
function generate_excel(tableid) {
  var table= document.getElementById(tableid);
  var html = table.outerHTML;
  window.open('data:application/vnd.ms-excel;base64,' + base64_encode(html));
}

function base64_encode (data) {
  // http://kevin.vanzonneveld.net
  // +   original by: Tyler Akins (http://rumkin.com)
  // +   improved by: Bayron Guevara
  // +   improved by: Thunder.m
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Pellentesque Malesuada
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Rafal Kukawski (http://kukawski.pl)
  // *     example 1: base64_encode('Kevin van Zonneveld');
  // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  // mozilla has this native
  // - but breaks in 2.0.0.12!
  //if (typeof this.window['btoa'] == 'function') {
  //    return btoa(data);
  //}
  var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = "",
    tmp_arr = [];

  if (!data) {
    return data;
  }

  do { // pack three octets into four hexets
    o1 = data.charCodeAt(i++);
    o2 = data.charCodeAt(i++);
    o3 = data.charCodeAt(i++);

    bits = o1 << 16 | o2 << 8 | o3;

    h1 = bits >> 18 & 0x3f;
    h2 = bits >> 12 & 0x3f;
    h3 = bits >> 6 & 0x3f;
    h4 = bits & 0x3f;

    // use hexets to index into b64, and append result to encoded string
    tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  } while (i < data.length);

  enc = tmp_arr.join('');

  var r = data.length % 3;

  return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

}
</script>

答案 3 :(得分:5)

Excel Export Script works on IE7+ , Firefox and Chrome
===========================================================



function fnExcelReport()
    {
             var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
             var textRange; var j=0;
          tab = document.getElementById('headerTable'); // id of table


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

          tab_text=tab_text+"</table>";
          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 Sumit.xls");
                          }  
                  else                 //other browser not tested on IE 11
                      sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  


                      return (sa);
                            }

    Just Create a blank iframe
    enter code here
        <iframe id="txtArea1" style="display:none"></iframe>

    Call this function on

        <button id="btnExport" onclick="fnExcelReport();"> EXPORT 
        </button>

答案 4 :(得分:3)

    function XLExport() {
        try {
            var i;
            var j;
            var mycell;
            var tableID = "tblInnerHTML";

            var objXL = new ActiveXObject("Excel.Application");
            var objWB = objXL.Workbooks.Add();
            var objWS = objWB.ActiveSheet;

            for (i = 0; i < document.getElementById('<%= tblAuditReport.ClientID %>').rows.length; i++) {
                for (j = 0; j < document.getElementById('<%= tblAuditReport.ClientID %>').rows(i).cells.length; j++) {
                    mycell = document.getElementById('<%= tblAuditReport.ClientID %>').rows(i).cells(j);
                    objWS.Cells(i + 1, j + 1).Value = mycell.innerText;
                }
            }

            //objWS.Range("A1", "L1").Font.Bold = true;

            objWS.Range("A1", "Z1").EntireColumn.AutoFit();

            //objWS.Range("C1", "C1").ColumnWidth = 50;

            objXL.Visible = true;

        }
        catch (err) {
                    }

    }

答案 5 :(得分:1)

检查一下......我刚刚开始工作,看起来你正在努力做到这一点。

2个功能。一个选择表并将其复制到剪贴板,第二个将其写入excel en masse。只需调用write_to_excel()并输入您的表id(或修改它以将其作为参数)。

  function selectElementContents(el) {
        var body = document.body, range, sel;
        if (document.createRange && window.getSelection) {
            range = document.createRange();
            sel = window.getSelection();
            sel.removeAllRanges();
            try {
                range.selectNodeContents(el);
                sel.addRange(range);
            } catch (e) {
                range.selectNode(el);
                sel.addRange(range);
            }
        } else if (body.createTextRange) {
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
        }
        range.execCommand("Copy");
    }

function write_to_excel() 
{
var tableID = "AllItems";
selectElementContents( document.getElementById(tableID) );

var excel = new ActiveXObject("Excel.Application");
// excel.Application.Visible = true; 
var wb=excel.WorkBooks.Add();
var ws=wb.Sheets("Sheet1");
ws.Cells(1,1).Select;
ws.Paste;
ws.DrawingObjects.Delete;
ws.Range("A1").Select
 excel.Application.Visible = true; 
}

受到影响:Select a complete table with Javascript (to be copied to clipboard)

答案 6 :(得分:1)

检查https://github.com/linways/table-to-excel。 它是exceljs/exceljs的包装器,用于将html表导出到xlsx。

TableToExcel.convert(document.getElementById("simpleTable1"));
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel@v1.0.4/dist/tableToExcel.js"></script>
<table id="simpleTable1" data-cols-width="70,15,10">
<tbody>
    <tr>
        <td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="middle" data-f-underline="true">
            Sample Excel
        </td>
    </tr>
    <tr>
        <td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial" data-a-v="top">
            Italic and horizontal center in Arial
        </td>
    </tr>
    <tr>
        <th data-a-text-rotation="90">Col 1 (number)</th>
        <th data-a-text-rotation="vertical">Col 2</th>
        <th data-a-wrap="true">Wrapped Text</th>
        <th data-a-text-rotation="-45">Col 4 (date)</th>
        <th data-a-text-rotation="-90">Col 5</th>
    </tr>
    <tr>
        <td rowspan="1" data-t="n">1</td>
        <td rowspan="1" data-b-b-s="thick" data-b-l-s="thick" data-b-r-s="thick">
            ABC1
        </td>
        <td rowspan="1" data-f-strike="true">Striked Text</td>
        <td data-t="d">05-20-2018</td>
        <td data-t="n" data-num-fmt="$ 0.00">2210.00</td>
    </tr>

    <tr>
        <td rowspan="2" data-t="n">2</td>
        <td rowspan="2" data-fill-color="FFFF0000" data-f-color="FFFFFFFF">
            ABC 2
        </td>
        <td rowspan="2" data-a-indent="3">Merged cell</td>
        <td data-t="d">05-21-2018</td>
        <td data-t="n" data-b-a-s="dashed" data-num-fmt="$ 0.00">230.00</td>
    </tr>
    <tr>
        <td data-t="d">05-22-2018</td>

        <td data-t="n" data-num-fmt="$ 0.00">2493.00</td>
    </tr>

    <tr>
        <td colspan="4" align="right" data-f-bold="true" data-a-h="right" data-hyperlink="https://google.com">
            <b><a href="https://google.com">Hyperlink</a></b>
        </td>
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">
            <b>4933.00</b>
        </td>
    </tr>
    <tr>
        <td colspan="4" align="right" data-f-bold="true" data-a-rtl="true">
            مرحبا
        </td>
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">
            <b>2009.00</b>
        </td>
    </tr>
    <tr>
        <td data-b-a-s="dashed" data-b-a-c="FFFF0000">All borders</td>
    </tr>
    <tr>
        <td data-t="b">true</td>
        <td data-t="b">false</td>
        <td data-t="b">1</td>
        <td data-t="b">0</td>
        <td data-error="#VALUE!">Value Error</td>
    </tr>
    <tr>
        <td data-b-t-s="thick" data-b-l-s="thick" data-b-b-s="thick" data-b-r-s="thick" data-b-t-c="FF00FF00" data-b-l-c="FF00FF00" data-b-b-c="FF00FF00" data-b-r-c="FF00FF00">
            All borders separately
        </td>
    </tr>
    <tr data-exclude="true">
        <td>Excluded row</td>
        <td>Something</td>
    </tr>
    <tr>
        <td>Included Cell</td>
        <td data-exclude="true">Excluded Cell</td>
        <td>Included Cell</td>
    </tr>
</tbody>
</table>

这会在客户端创建有效的xlsx。还支持一些基本样式。请查看https://codepen.io/rohithb/pen/YdjVbb以获取有效工作示例。

答案 7 :(得分:0)

我认为您也可以考虑其他架构。有时可以通过其他方式更轻松地完成某些事情。如果您是HTML文件的生产者,那么您可以编写HTTP处理程序以在服务器上创建Excel文档(这比在JavaScript中更容易)并将文件发送到客户端。如果您从某个地方(如报告的HTML版本)收到该HTML文件,那么您仍然可以使用C#或PHP等服务器端语言来创建Excel文件。我的意思是,你也可能有其他方法。 :)

答案 8 :(得分:0)

我用jquery尝试这个; 使用它,玩得开心:D

    jQuery.printInExcel = function (DivID) 
{ 
var ExcelApp = new ActiveXObject("Excel.Application"); 
ExcelApp.Workbooks.Add; 
ExcelApp.visible = true; 
var str = ""; 
var tblcount = 0; 
var trcount = 0;
 $("#" + DivID + " table").each(function () 
{ $(this).find("tr").each(function () 
{ var tdcount = 0; $(this).find("td").each(function () 
{ str = str + $(this).text(); ExcelApp.Cells(trcount + 1, tdcount + 1).Value = str; 
str = ""; tdcount++ 
}); 
trcount++ 
}); tblcount++ 
}); 
};

在你的班级中使用它并用$ .printInExcel(你的var )调用它;

答案 9 :(得分:0)

我建议使用不同的方法。在网页上添加一个按钮,该按钮将表格的内容复制到剪贴板,列之间有TAB字符,行之间有换行符。这样,Excel中的“粘贴”功能应该可以正常工作,您的Web应用程序也可以在许多浏览器和许多操作系统(Linux,Mac,移动设备)上使用,用户也可以将这些数据与其他电子表格或文字处理一起使用程序

唯一棘手的部分是复制到剪贴板,因为很多浏览器都很痴迷于此。一种解决方案是准备已在textarea中选择的数据,并在模式对话框中向用户显示,告诉用户复制文本(有些人需要输入Ctrl-C,其他人需要输入Command-c,其他人则需要使用“长按”或弹出菜单。

拥有可能要求用户确认的标准复制到剪贴板功能会更好......但不幸的是,情况并非如此。