JavaScript를 사용하여 HTML 테이블 데이터를 Excel로 내보내기 / JQuery가 Chrome 브라우저에서 제대로 작동하지 않습니다.


91

속도 템플릿에 HTML 테이블이 있습니다. 모든 브라우저와 호환되는 Java 스크립트 또는 jquery를 사용하여 html 테이블 데이터를 Excel로 내보내고 싶습니다. 아래 스크립트를 사용하고 있습니다.

<script type="text/javascript">
function ExportToExcel(mytblId){
       var htmltable= document.getElementById('my-table-id');
       var html = htmltable.outerHTML;
       window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
    }
</script>

이 스크립트는 Mozilla Firefox 에서 잘 작동 하며 Excel 대화 상자와 함께 팝업되고 열기 또는 저장 옵션을 요청합니다. 그러나 Chrome 브라우저 에서 동일한 스크립트를 테스트했을 때 예상대로 작동하지 않으며 버튼을 클릭하면 Excel에 대한 팝업이 없습니다. 데이터는 "file type : file", 확장자가 .xls 와 같은 파일로 다운로드 됩니다. Chrome 콘솔에 오류가 없습니다.

Jsfiddle 예 :

http://jsfiddle.net/insin/cmewv/

이것은 mozilla에서는 잘 작동하지만 크롬에서는 작동하지 않습니다.

Chrome 브라우저 테스트 사례 :

첫 번째 이미지 : Excel로 내보내기 버튼을 클릭합니다.

첫 번째 이미지 : Excel로 내보내기 버튼을 클릭합니다.

결과 :

결과


테스트 케이스는 크롬입니다
Sukane

1
오픈 소스 제품인 LibreOffice 및 Chrome 브라우저를 사용하는 경우 위의 테스트 사례가 실패합니다. 그러나 MS Office가 설치되어 있으면 코드가 제대로 작동합니다.
Sukane

답변:


168

Excel 내보내기 스크립트는 IE7 +, Firefox 및 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);
}

빈 iframe을 만드십시오.

<iframe id="txtArea1" style="display:none"></iframe>

다음에서이 함수를 호출합니다.

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

1
그렇지 않다면이 라인은 무엇입니까 ?? var txt = document.getElementById ( 'txtArea1'). contentWindow;
sampopes 2014-06-20

3
Chrome에서 다운로드 버튼을 클릭해도이 방법을 사용할 때 아무 일도 일어나지 않습니다. 콘솔 오류 또는 아무것도 없습니다.
Kyle Bachan 2014

1
완벽한 +1 !!! IE 11, Chrome 35, Firefox 29, Opera 17에서 작동하지만 safari 5.1.7에서는 작동하지 않습니다! :(
Suganth G 2014

9
Randome 이름을 어떻게 변경할 수 있습니까? 특정 이름을 설정했습니다.
osman Rahimi

21
"download.xls의 파일 형식과 확장자가 일치하지 않습니다."이것은 관리자를 행복하게하지 않습니다.
Tom Stickel 2015 년

36

Datatable 플러그인은 목적을 가장 잘 해결하고 HTML 테이블 데이터를 Excel, PDF, TEXT로 내보낼 수 있습니다. 쉽게 구성 할 수 있습니다.

아래 데이터 테이블 참조 링크에서 전체 예를 찾으십시오.

https://datatables.net/extensions/buttons/examples/html5/simple.html

(데이터 테이블 참조 사이트의 스크린 샷) 여기에 이미지 설명 입력


4
OMG! 이것은 멋진 플러그인입니다! ... 그리고 여러 플러그인이 포함되어 있습니다 !! 내보내기, 정렬, 재정렬, 인쇄 미리보기 등 ... 단 한 번의 샷으로 필요한 모든 데이터를 해결했습니다!
Gusstavv Gil 2010 년

이 플러그인을 사용하여 Excel에 스타일을 적용 할 수 있습니까?
Shruthi Sathyanarayana

@ Addy 이것은 DataTables 전용 솔루션입니다.
Karl

1
두 항목을 모두 유지하려면 내보내기 버튼이 각 페이지 행 개수 드롭 다운을 제거합니다. 해결 하려면 datatables.net/extensions/buttons/examples/initialisation/… 을 확인 하십시오.
Kaushik Das

플러그인은 훌륭합니다. 데이터를 내보내고 여기에서 강조 표시하기 위해 관련 코드를 추출하는 방법이 있습니까? 그것은 큰 도움이 될 것입니다. 미리 감사드립니다
Murtuza Husain

31

이것은 도움이 될 수 있습니다

function exportToExcel(){
var htmls = "";
            var uri = 'data:application/vnd.ms-excel;base64,';
            var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'; 
            var base64 = function(s) {
                return window.btoa(unescape(encodeURIComponent(s)))
            };

            var format = function(s, c) {
                return s.replace(/{(\w+)}/g, function(m, p) {
                    return c[p];
                })
            };

            htmls = "YOUR HTML AS TABLE"

            var ctx = {
                worksheet : 'Worksheet',
                table : htmls
            }


            var link = document.createElement("a");
            link.download = "export.xls";
            link.href = uri + base64(format(template, ctx));
            link.click();
}

1
HTML 테이블에 표시되는 열만 내보내려면 어떻게해야합니까 ??
Nouman Bhatti

안녕하세요, 시트로 EXCEL 연산을 수행 할 수 없습니다 (예 : Autosum). 이 EXCEL 시트의 데이터 형식이나 다른 문제 때문입니까 .. 일부 작업을 수행하는 데 도움이 필요합니다.
Nanda Kishore Allu

9

http://wsnippets.com/export-html-table-data-excel-sheet-using-jquery/ 이 링크를 시도하면 문제가 해결 될 수 있습니다.

여기에 이미지 설명 입력


Uchit, 답변 해 주셔서 감사합니다.하지만 이미이 예제를 시도했습니다. 언급했듯이 Mozilla에서는 잘 작동하지만 Chorme에서는 작동하지 않습니다 .Chrome 브라우저에서이 예제를 시도해 볼 수 있습니까?
Sukane 2014 년

5
jsfiddle에서 귀하의 코드를 시도했으며 긍정적 인 결과를 얻었습니다. chorme에서도 잘 작동합니다. 당신은 다운로드가 sucessfull 것을 위의 이미지에서 볼 수
Uchit 쉬 레스타

1
Uchit, 고마워. 네 코드가 작동합니다. 문제는 내가 Libre Office를 사용하고 있었기 때문에 Chrome 내보내기에서 Excel로 제대로 작동하지 않았습니다 (m 질문의 스크린 샷 참조). 그러나 당신이 언급했듯이 MS 오피스에서는 작동합니다. 이에 대한 jQuery 코드를 제공해 주셔서 감사합니다.
Sukane

이 함수는 드롭 다운 및 타임 스탬프가있는 필드의 값을 내 보내지 않습니다.
SNT93

다중 테이블 html에서는 작동하지 않으며 하나의 테이블에서만 작동합니다. 다중 테이블로 어떻게이 작업을 수행 할 수 있습니까 ??????
ignacio chiazzo

9

window.open사용하는 대신 onclick이벤트 와 함께 링크를 사용할 수 있습니다 .
그리고 html 테이블을 uri에 넣고 다운로드 할 파일 이름을 설정할 수 있습니다.

라이브 데모 :

function exportF(elem) {
  var table = document.getElementById("table");
  var html = table.outerHTML;
  var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url 
  elem.setAttribute("href", url);
  elem.setAttribute("download", "export.xls"); // Choose the file name
  return false;
}
<table id="table" border="1">
  <tr>
    <td>
      Foo
    </td>
    <td>
      Bar
    </td>
  </tr>
</table>

<a id="downloadLink" onclick="exportF(this)">Export to excel</a>


함수에서 테이블 테두리, td 너비 등을 어떻게 설정할 수 있습니까?
Zeffry Reynando

9

TableExport

TableExport -HTML 테이블을 xlsx, xls, csv 및 txt 파일로 내보내는 간단하고 구현하기 쉬운 라이브러리입니다.

이 라이브러리를 사용하려면 TableExport생성자를 호출하면됩니다 .

new TableExport(document.getElementsByTagName("table"));

// OR simply

TableExport(document.getElementsByTagName("table"));

// OR using jQuery

$("table").tableExport(); 

테이블, 버튼 및 내 보낸 데이터의 모양과 느낌을 사용자 지정하기 위해 추가 속성을 전달할 수 있습니다. 여기에서 더 많은 정보를보십시오


PhantomJ를 지원합니까? 버그를보고하는 방법?
골리 마르

6

이 예의 병합 :

https://www.codexworld.com/export-html-table-data-to-excel-using-javascript https://bl.ocks.org/Flyer53/1de5a78de9c89850999c

function exportTableToExcel(tableId, filename) {
    let dataType = 'application/vnd.ms-excel';
    let extension = '.xls';

    let base64 = function(s) {
        return window.btoa(unescape(encodeURIComponent(s)))
    };

    let template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
    let render = function(template, content) {
        return template.replace(/{(\w+)}/g, function(m, p) { return content[p]; });
    };

    let tableElement = document.getElementById(tableId);

    let tableExcel = render(template, {
        worksheet: filename,
        table: tableElement.innerHTML
    });

    filename = filename + extension;

    if (navigator.msSaveOrOpenBlob)
    {
        let blob = new Blob(
            [ '\ufeff', tableExcel ],
            { type: dataType }
        );

        navigator.msSaveOrOpenBlob(blob, filename);
    } else {
        let downloadLink = document.createElement("a");

        document.body.appendChild(downloadLink);

        downloadLink.href = 'data:' + dataType + ';base64,' + base64(tableExcel);

        downloadLink.download = filename;

        downloadLink.click();
    }
}

1
잡히지 않은 ReferenceError : base64가 정의되지 않았습니다
Pedro Joaquín


4

sampopes와 관련하여 2014 년 6 월 6 일 11:59 :

Excel 데이터를 더 크게 표시하기 위해 글꼴 크기가 20px 인 CSS 스타일을 삽입했습니다. sampopes 코드에서 선행 <tr>태그가 누락되었으므로 먼저 헤드 라인을 출력하고 루프 내의 다른 테이블 행보다 먼저 출력합니다.

function fnExcelReport()
{
    var tab_text = '<table border="1px" style="font-size:20px" ">';
    var textRange; 
    var j = 0;
    var tab = document.getElementById('DataTableId'); // id of table
    var lines = tab.rows.length;

    // the first headline of the table
    if (lines > 0) {
        tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
    }

    // table data lines, loop starting from 1
    for (j = 1 ; j < lines; j++) {     
        tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</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
    // console.log(tab_text); // aktivate so see the result (press F12 in browser)

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

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

    return (sa);
}   

Excel로 내보내는 특정 열을 제거하는 방법을 알려주세요. 예를 들어, 피하고 싶습니다 tab.rows[j].cells[13] . 귀하의 도움에 감사드립니다
Disera

아주 좋은 대답입니다. 아주 간단한 테이블의 경우 마지막 줄만 유지하겠습니다 window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));. enconding은 매우 중요합니다.
Pere Pages

4

 function exportToExcel() {
        var tab_text = "<tr bgcolor='#87AFC6'>";
        var textRange; var j = 0, rows = '';
        tab = document.getElementById('student-detail');
        tab_text = tab_text + tab.rows[0].innerHTML + "</tr>";
        var tableData = $('#student-detail').DataTable().rows().data();
        for (var i = 0; i < tableData.length; i++) {
            rows += '<tr>'
                + '<td>' + tableData[i].value1 + '</td>'
                + '<td>' + tableData[i].value2 + '</td>'
                + '<td>' + tableData[i].value3 + '</td>'
                + '<td>' + tableData[i].value4 + '</td>'
                + '<td>' + tableData[i].value5 + '</td>'
                + '<td>' + tableData[i].value6 + '</td>'
                + '<td>' + tableData[i].value7 + '</td>'
                + '<td>' +  tableData[i].value8 + '</td>'
                + '<td>' + tableData[i].value9 + '</td>'
                + '<td>' + tableData[i].value10 + '</td>'
                + '</tr>';
        }
        tab_text += rows;
        var data_type = 'data:application/vnd.ms-excel;base64,',
            template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border="2px">{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];
                })
            }

        var ctx = {
            worksheet: "Sheet 1" || 'Worksheet',
            table: tab_text
        }
        document.getElementById("dlink").href = data_type + base64(format(template, ctx));
        document.getElementById("dlink").download = "StudentDetails.xls";
        document.getElementById("dlink").traget = "_blank";
        document.getElementById("dlink").click();
    }

여기서 값 1에서 10은 얻는 열 이름입니다.


4

tableToExcel.js 를 사용할 수 있습니다. 를 하여 Excel 파일로 테이블을 내보낼 .

이것은 다음과 같은 방식으로 작동합니다.

1). 프로젝트 / 파일에이 CDN 포함

<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel@v1.0.4/dist/tableToExcel.js"></script>

2). JavaScript 사용 :

<button id="btnExport" onclick="exportReportToExcel(this)">EXPORT REPORT</button>

function exportReportToExcel() {
  let table = document.getElementsByTagName("table"); // you can use document.getElementById('tableId') as well by providing id to the table tag
  TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
    name: `export.xlsx`, // fileName you could use any name
    sheet: {
      name: 'Sheet 1' // sheetName
    }
  });
}

삼). 또는 Jquery를 사용하여

<button id="btnExport">EXPORT REPORT</button>

$(document).ready(function(){
    $("#btnExport").click(function() {
        let table = document.getElementsByTagName("table");
        TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
           name: `export.xlsx`, // fileName you could use any name
           sheet: {
              name: 'Sheet 1' // sheetName
           }
        });
    });
});

다른 정보는이 github 링크를 참조 할 수 있습니다.

https://github.com/linways/table-to-excel/tree/master

또는 라이브 예제를 참조하려면 다음 링크를 방문하십시오.

https://codepen.io/rohithb/pen/YdjVbb

이것이 누군가를 도울 수 있기를 바랍니다 :-)


1

내 버전의 @sampopes 답변

function exportToExcel(that, id, hasHeader, removeLinks, removeImages, removeInputParams) {
if (that == null || typeof that === 'undefined') {
    console.log('Sender is required');
    return false;
}

if (!(that instanceof HTMLAnchorElement)) {
    console.log('Sender must be an anchor element');
    return false;
}

if (id == null || typeof id === 'undefined') {
    console.log('Table id is required');
    return false;
}
if (hasHeader == null || typeof hasHeader === 'undefined') {
    hasHeader = true;
}
if (removeLinks == null || typeof removeLinks === 'undefined') {
    removeLinks = true;
}
if (removeImages == null || typeof removeImages === 'undefined') {
    removeImages = false;
}
if (removeInputParams == null || typeof removeInputParams === 'undefined') {
    removeInputParams = true;
}

var tab_text = "<table border='2px'>";
var textRange;

tab = $(id).get(0);

if (tab == null || typeof tab === 'undefined') {
    console.log('Table not found');
    return;
}

var j = 0;

if (hasHeader && tab.rows.length > 0) {
    var row = tab.rows[0];
    tab_text += "<tr bgcolor='#87AFC6'>";
    for (var l = 0; l < row.cells.length; l++) {
        if ($(tab.rows[0].cells[l]).is(':visible')) {//export visible cols only
            tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
        }
    }
    tab_text += "</tr>";
    j++;
}

for (; j < tab.rows.length; j++) {
    var row = tab.rows[j];
    tab_text += "<tr>";
    for (var l = 0; l < row.cells.length; l++) {
        if ($(tab.rows[j].cells[l]).is(':visible')) {//export visible cols only
            tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
        }
    }
    tab_text += "</tr>";
}

tab_text = tab_text + "</table>";
if (removeLinks)
    tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");
if (removeImages)
    tab_text = tab_text.replace(/<img[^>]*>/gi, ""); 
if (removeInputParams)
    tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, "");

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

if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
{
    myIframe.document.open("txt/html", "replace");
    myIframe.document.write(tab_text);
    myIframe.document.close();
    myIframe.focus();
    sa = myIframe.document.execCommand("SaveAs", true, document.title + ".xls");
    return true;
}
else {
    //other browser tested on IE 11
    var result = "data:application/vnd.ms-excel," + encodeURIComponent(tab_text);
    that.href = result;
    that.download = document.title + ".xls";
    return true;
}
}

iframe이 필요합니다.

<iframe id="myIframe" style="opacity: 0; width: 100%; height: 0px;" seamless="seamless"></iframe>

용법

$("#btnExportToExcel").click(function () {
    exportToExcel(this, '#mytable');
});
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.