복붙노트

[JQUERY] 자바 스크립트 / jQuery를 사용하여 Excel로 내보내기 HTML 테이블 데이터는 크롬 브라우저에서 제대로 작동하지 않습니다

JQUERY

자바 스크립트 / jQuery를 사용하여 Excel로 내보내기 HTML 테이블 데이터는 크롬 브라우저에서 제대로 작동하지 않습니다

해결법


  1. 1.엑셀 수출 스크립트는 IE7 +, 파이어 폭스와 크롬에서 작동합니다.

    엑셀 수출 스크립트는 IE7 +, 파이어 폭스와 크롬에서 작동합니다.

    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>
    

  2. 2.데이터 테이블 플러그인은 목적 최선을 해결하고 엑셀, PDF, 텍스트에 HTML 테이블 데이터를 내보낼 수있게 해준다. 쉽게 구성.

    데이터 테이블 플러그인은 목적 최선을 해결하고 엑셀, PDF, 텍스트에 HTML 테이블 데이터를 내보낼 수있게 해준다. 쉽게 구성.

    데이터 테이블 참조 링크 아래에있는 전체 예제를 찾아주세요 :

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

    (데이터 테이블 기준 사이트 화면)


  3. 3.이 도움이 될 수

    이 도움이 될 수

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

  4. 4.http://wsnippets.com/export-html-table-data-excel-sheet-using-jquery/ 이 문제를 해결할 수있는이 링크를 시도하십시오

    http://wsnippets.com/export-html-table-data-excel-sheet-using-jquery/ 이 문제를 해결할 수있는이 링크를 시도하십시오


  5. 5.대신 당신이 온 클릭 이벤트에 링크를 사용할 수 있습니다 window.open 사용. 그리고 당신은 URI에 HTML 테이블을 넣어 다운로드 할 파일 이름을 설정할 수 있습니다.

    대신 당신이 온 클릭 이벤트에 링크를 사용할 수 있습니다 window.open 사용. 그리고 당신은 URI에 HTML 테이블을 넣어 다운로드 할 파일 이름을 설정할 수 있습니다.

    라이브 데모 :

    함수 exportF (ELEM) { VAR 테이블은 document.getElementById를 ( "테이블") =; VAR HTML = table.outerHTML; var에 URL = '데이터 : 응용 프로그램 / vnd.ms-엑셀,'+ 탈출 (HTML) // URL로 HTML 테이블을 설정 elem.setAttribute ( "HREF", URL); elem.setAttribute ( "다운로드", "export.xls"); 파일 이름을 선택합니다 // false를 반환; } <테이블 ID = "테이블"테두리 = "1"> 푸 엑셀로 수출


  6. 6.

    TABLEEXPORT - 간단한은 수출 HTML의 XLSX, XLS, CSV로 테이블 및 TXT 파일을 라이브러리를 구현하기 쉬운.

    이 라이브러리, 간단한 호출 TABLEEXPORT 생성자를 사용하려면 :

    new TableExport(document.getElementsByTagName("table"));
    
    // OR simply
    
    TableExport(document.getElementsByTagName("table"));
    
    // OR using jQuery
    
    $("table").tableExport(); 
    

    추가 속성은 전달 된 수있는 모양을 사용자 정의하고 테이블, 버튼, 내 보낸 데이터의 느낌. 여기에 더 많은 정보를보기


  7. 7.이 예제의 내 병합 :

    이 예제의 내 병합 :

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

  8. 8.ShieldUI 그렇게하는 것처럼 당신은 라이브러리를 사용할 수 있습니다.

    ShieldUI 그렇게하는 것처럼 당신은 라이브러리를 사용할 수 있습니다.

    그것은 XML 및 XLSX 널리 사용되는 엑셀 형식 모두에 수출을 지원합니다.

    더 자세한 사항은 여기에 : http://demos.shieldui.com/web/grid-general/export-to-excel


  9. 9.sampopes에 관련하여 11시 59분에서 6월 6일 '14에서 답변 :

    sampopes에 관련하여 11시 59분에서 6월 6일 '14에서 답변 :

    나는 엑셀 데이터 이상을 표시 할 20 픽셀의 글꼴 크기와 CSS 스타일을 삽입 할 수 있습니다. sampopes 코드에서 선도적 인 태그 누락, 내가 먼저 출력 제목 있도록 루프 내에서 다른 테이블의 행보다.

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

  10. 10.exportToExcel 함수 () { var에 tab_text = ""; VAR textRange; VAR의 J = 0, 로우 = ""; 탭 = document.getElementById를 ( '학생 세부 사항'); tab_text = tab_text + tab.rows [0] .innerHTML + ""; VAR tableData = $ ( '# 학생 세부 사항')의 DataTable () 행 () 데이터 ()...; 경우 (나는 '+ tableData [I] .value1 + '' + ''+ tableData [I] .value2 + '' + ''+ tableData [I] .value3 + '' + ''+ tableData [I] .value4 + '' + ''+ tableData [I] .value5 + '' + ''+ tableData [I] .value6 + '' + ''+ tableData [I] .value7 + '' + ''+ tableData [I] .value8 + '' + ''+ tableData [I] .value9 + '' + ''+ tableData [I] .value10 + '' + ''; } tab_text + = 로우; var에 DATA_TYPE = '데이터 : 응용 프로그램 / vnd.ms-엑셀,베이스 64', 템플릿 = ' {워크 시트} < X / 이름> <[ENDIF] - -> <표 테두리 = "2 픽셀"> {TABLE} ", 64 기수 = 기능 (들) { 반환 window.btoa (언 이스케이프 (에 encodeURIComponent (들))) }, 포맷 = 함수 (S, C) { 리턴 s.replace (/ {(\ w +)} / g, 함수 (m, p)를 { C [P]를 복귀; }) } var에 CTX = { 워크 시트 : "시트 1"|| '워크 시트', 테이블 : tab_text } document.getElementById를 ( "DLINK") HREF = DATA_TYPE +베이스 64 (형식 (템플릿 CTX)).; document.getElementById를 ( "DLINK") 다운로드 = "StudentDetails.xls."; document.getElementById를 ( "DLINK") traget = "_blank."; . document.getElementById를은 ( "DLINK")) (클릭; }

    exportToExcel 함수 () { var에 tab_text = ""; VAR textRange; VAR의 J = 0, 로우 = ""; 탭 = document.getElementById를 ( '학생 세부 사항'); tab_text = tab_text + tab.rows [0] .innerHTML + ""; VAR tableData = $ ( '# 학생 세부 사항')의 DataTable () 행 () 데이터 ()...; 경우 (나는 '+ tableData [I] .value1 + '' + ''+ tableData [I] .value2 + '' + ''+ tableData [I] .value3 + '' + ''+ tableData [I] .value4 + '' + ''+ tableData [I] .value5 + '' + ''+ tableData [I] .value6 + '' + ''+ tableData [I] .value7 + '' + ''+ tableData [I] .value8 + '' + ''+ tableData [I] .value9 + '' + ''+ tableData [I] .value10 + '' + ''; } tab_text + = 로우; var에 DATA_TYPE = '데이터 : 응용 프로그램 / vnd.ms-엑셀,베이스 64', 템플릿 = ' {워크 시트} < X / 이름> <[ENDIF] - -> <표 테두리 = "2 픽셀"> {TABLE} ", 64 기수 = 기능 (들) { 반환 window.btoa (언 이스케이프 (에 encodeURIComponent (들))) }, 포맷 = 함수 (S, C) { 리턴 s.replace (/ {(\ w +)} / g, 함수 (m, p)를 { C [P]를 복귀; }) } var에 CTX = { 워크 시트 : "시트 1"|| '워크 시트', 테이블 : tab_text } document.getElementById를 ( "DLINK") HREF = DATA_TYPE +베이스 64 (형식 (템플릿 CTX)).; document.getElementById를 ( "DLINK") 다운로드 = "StudentDetails.xls."; document.getElementById를 ( "DLINK") traget = "_blank."; . document.getElementById를은 ( "DLINK")) (클릭; }

    여기에 10 값 1은 받고 있는지 열 이름은


  11. 11.당신은 엑셀 파일에 테이블을 내보낼 tableToExcel.js를 사용할 수 있습니다.

    당신은 엑셀 파일에 테이블을 내보낼 tableToExcel.js를 사용할 수 있습니다.

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

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

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

    2). 어느 자바 스크립트를 사용 :

    <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

    이 의지 도움말 사람을 희망 :-)


  12. 12.@sampopes 응답의 내 버전

    @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');
    });
    
  13. from https://stackoverflow.com/questions/22317951/export-html-table-data-to-excel-using-javascript-jquery-is-not-working-properl by cc-by-sa and MIT license