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

时间:2022-10-12 09:56:29

My table is in format

我的表格式

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

I found the following code online. But it doesn't work if i use "thead" and "tbody" tags

我在网上找到了以下代码。但如果我使用“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 个解决方案

#1


5  

The reason the solution you found on the internet is no working is because of the line that starts var colCount. The variable mytable only has two elements being <thead> and <tbody>. The var colCount line is looking for all the elements within mytable that are <tr>. The best thing you can do is give an id to your <thead> and <tbody> and then grab all the values based on that. Say you had <thead id='headers'> :

您在互联网上找到的解决方案无法正常工作的原因是因为启动var colCount的行。变量mytable只有两个元素是和。 var colCount行正在查找mytable中的所有元素。你可以做的最好的事情是给你的和一个id,然后根据它获取所有的值。假设你有:

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

}

and then do the same thing for the <tbody> tag.

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

EDIT: I would also highly recommend using jQuery. It would shorten this up to:

编辑:我也强烈建议使用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;
  });
}

Now, of course, this is going to give you some formatting issues but you can work out how you want it formatted in Excel.

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

EDIT: To answer your question about how to do this for n number of tables, the jQuery will do this already. To do it in raw Javascript, grab all the tables and then alter the function to be able to pass in the table as a parameter. For instance:

编辑:要回答关于如何为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]);
}

Then change the function write_headers_to_excel() to function write_headers_to_excel(table). Then change var myTableHead = document.getElementById('headers'); to var myTableHead = table.getElementsByTagName('thead')[0];. Same with your write_bodies_to_excel() or however you want to set that up.

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

#2


8  

Only works in Mozilla, Chrome and Safari..

仅适用于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>

#3


5  

This might be a better answer copied from this question. Please try it and give opinion here. Please vote up if found useful. Thank you.

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

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

#4


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>

#5


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) {
                    }

    }

#6


1  

Check this out... I just got this working and it seems exactly what you are trying to do as well.

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

2 functions. One to select the table and copy it to the clipboard, and the second writes it to excel en masse. Just call write_to_excel() and put in your table id (or modify it to take it as an argument).

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

Heavily influenced from: Select a complete table with Javascript (to be copied to clipboard)

深受影响:用Javascript选择一个完整的表格(要复制到剪贴板)

#7


0  

I think you can also think of alternative architectures. Sometimes something can be done in another way much more easier. If the producer of HTML file is you, then you can write an HTTP handler to create an Excel document on the server (which is much more easier than in JavaScript) and send a file to the client. If you receive that HTML file from somewhere (like an HTML version of a report), then you still can use a server side language like C# or PHP to create the Excel file still very easily. I mean, you may have other ways too. :)

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

#8


0  

I would suggest using a different approach. Add a button on the webpage that will copy the content of the table to the clipboard, with TAB chars between columns and newlines between rows. This way the "paste" function in Excel should work correctly and your web application will also work with many browsers and on many operating systems (linux, mac, mobile) and users will be able to use the data also with other spreadsheets or word processing programs.

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

The only tricky part is to copy to the clipboard because many browsers are security obsessed on this. A solution is to prepare the data already selected in a textarea, and show it to the user in a modal dialog box where you tell the user to copy the text (some will need to type Ctrl-C, others Command-c, others will use a "long touch" or a popup menu).

唯一棘手的部分是复制到剪贴板,因为许多浏览器都是安全痴迷于此。解决方案是准备已在textarea中选择的数据,并在模式对话框中将其显示给用户,在该对话框中您告诉用户复制文本(一些将需要键入Ctrl-C,其他键入命令-c,其他将使用“长触摸”或弹出菜单)。

It would be nicer to have a standard copy-to-clipboard function that possibly requests a user confirmation... but this is not the case, unfortunately.

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

#9


0  

I try this with jquery; use this and have fun :D

我用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++ 
}); 
};

use this in your class and call it with $.printInExcel(your var);

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

#10


0  

Check https://github.com/linways/table-to-excel. Its a wrapper for js-xlsx to export html tables to xlsx.

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

 XLSX.utils.html.save_table_as_excel(document.getElementById('test-html-table'), {name: 'test.xlsx'});
<script src="https://cdn.rawgit.com/linways/table-to-excel/master/dist/xlsx_html.full.min.js"></script>
<table border="1" class="" width="100%" id="test-html-table" data-cols-width="20,15,10">
        <tbody><tr>
            <td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="center" data-f-underline="true">
                Sample Excel
            </td>
        </tr>
        <tr >
            <td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial">
                Italic and horizontal center in Arial
            </td>
        </tr>
        <tr>
            <th data-a-text-rotation="90">Col 1 (number)</th>
            <th data-a-text-rotation="90">Col 2</th>
            <th data-a-wrap="true">Wrapped Text</th>
            <th data-a-text-rotation="90">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" >
                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"><b>Total</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>
        </tbody></table>

This creates valid xlsx on the client side. Also supports some basic styling.

这会在客户端创建有效的xlsx。还支持一些基本样式。

#1


5  

The reason the solution you found on the internet is no working is because of the line that starts var colCount. The variable mytable only has two elements being <thead> and <tbody>. The var colCount line is looking for all the elements within mytable that are <tr>. The best thing you can do is give an id to your <thead> and <tbody> and then grab all the values based on that. Say you had <thead id='headers'> :

您在互联网上找到的解决方案无法正常工作的原因是因为启动var colCount的行。变量mytable只有两个元素是和。 var colCount行正在查找mytable中的所有元素。你可以做的最好的事情是给你的和一个id,然后根据它获取所有的值。假设你有:

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

}

and then do the same thing for the <tbody> tag.

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

EDIT: I would also highly recommend using jQuery. It would shorten this up to:

编辑:我也强烈建议使用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;
  });
}

Now, of course, this is going to give you some formatting issues but you can work out how you want it formatted in Excel.

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

EDIT: To answer your question about how to do this for n number of tables, the jQuery will do this already. To do it in raw Javascript, grab all the tables and then alter the function to be able to pass in the table as a parameter. For instance:

编辑:要回答关于如何为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]);
}

Then change the function write_headers_to_excel() to function write_headers_to_excel(table). Then change var myTableHead = document.getElementById('headers'); to var myTableHead = table.getElementsByTagName('thead')[0];. Same with your write_bodies_to_excel() or however you want to set that up.

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

#2


8  

Only works in Mozilla, Chrome and Safari..

仅适用于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>

#3


5  

This might be a better answer copied from this question. Please try it and give opinion here. Please vote up if found useful. Thank you.

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

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

#4


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>

#5


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) {
                    }

    }

#6


1  

Check this out... I just got this working and it seems exactly what you are trying to do as well.

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

2 functions. One to select the table and copy it to the clipboard, and the second writes it to excel en masse. Just call write_to_excel() and put in your table id (or modify it to take it as an argument).

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

Heavily influenced from: Select a complete table with Javascript (to be copied to clipboard)

深受影响:用Javascript选择一个完整的表格(要复制到剪贴板)

#7


0  

I think you can also think of alternative architectures. Sometimes something can be done in another way much more easier. If the producer of HTML file is you, then you can write an HTTP handler to create an Excel document on the server (which is much more easier than in JavaScript) and send a file to the client. If you receive that HTML file from somewhere (like an HTML version of a report), then you still can use a server side language like C# or PHP to create the Excel file still very easily. I mean, you may have other ways too. :)

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

#8


0  

I would suggest using a different approach. Add a button on the webpage that will copy the content of the table to the clipboard, with TAB chars between columns and newlines between rows. This way the "paste" function in Excel should work correctly and your web application will also work with many browsers and on many operating systems (linux, mac, mobile) and users will be able to use the data also with other spreadsheets or word processing programs.

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

The only tricky part is to copy to the clipboard because many browsers are security obsessed on this. A solution is to prepare the data already selected in a textarea, and show it to the user in a modal dialog box where you tell the user to copy the text (some will need to type Ctrl-C, others Command-c, others will use a "long touch" or a popup menu).

唯一棘手的部分是复制到剪贴板,因为许多浏览器都是安全痴迷于此。解决方案是准备已在textarea中选择的数据,并在模式对话框中将其显示给用户,在该对话框中您告诉用户复制文本(一些将需要键入Ctrl-C,其他键入命令-c,其他将使用“长触摸”或弹出菜单)。

It would be nicer to have a standard copy-to-clipboard function that possibly requests a user confirmation... but this is not the case, unfortunately.

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

#9


0  

I try this with jquery; use this and have fun :D

我用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++ 
}); 
};

use this in your class and call it with $.printInExcel(your var);

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

#10


0  

Check https://github.com/linways/table-to-excel. Its a wrapper for js-xlsx to export html tables to xlsx.

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

 XLSX.utils.html.save_table_as_excel(document.getElementById('test-html-table'), {name: 'test.xlsx'});
<script src="https://cdn.rawgit.com/linways/table-to-excel/master/dist/xlsx_html.full.min.js"></script>
<table border="1" class="" width="100%" id="test-html-table" data-cols-width="20,15,10">
        <tbody><tr>
            <td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="center" data-f-underline="true">
                Sample Excel
            </td>
        </tr>
        <tr >
            <td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial">
                Italic and horizontal center in Arial
            </td>
        </tr>
        <tr>
            <th data-a-text-rotation="90">Col 1 (number)</th>
            <th data-a-text-rotation="90">Col 2</th>
            <th data-a-wrap="true">Wrapped Text</th>
            <th data-a-text-rotation="90">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" >
                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"><b>Total</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>
        </tbody></table>

This creates valid xlsx on the client side. Also supports some basic styling.

这会在客户端创建有效的xlsx。还支持一些基本样式。