JavaScript/JQuery를 사용하여 HTML 테이블 데이터를 Excel로 내보내는 것이 Chrome 브라우저에서 제대로 작동하지 않습니다.
속도 템플릿에 HTML 표가 있습니다.모든 브라우저에서 자바 스크립트 또는 jquery, comatibale을 사용하여 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와 같은 확장자가 없습니다.크롬 콘솔에는 오류가 없습니다.
Jsfiddle의 예:
http://jsfiddle.net/insin/cmewv/
이것은 Mozilla에서는 정상적으로 동작하지만 Chrome에서는 동작하지 않습니다.
Chrome 브라우저 테스트 케이스:
첫 번째 이미지:Export to Excel 버튼을 클릭합니다.
결과:

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>
Datatable 플러그인은 목적을 가장 잘 해결하며 HTML 테이블 데이터를 Excel, PDF, TEXT로 쉽게 구성할 수 있습니다.
아래 데이터 테이블 참조 링크에서 전체 예를 확인하십시오.
https://datatables.net/extensions/buttons/examples/html5/simple.html
(데이터 가능 참조 사이트에서 복사)
이것이 도움이 될 것이다.
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();
}
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
}
});
}
3) 또는 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
이것이 누군가에게 도움이 되기를 바랍니다:-)
사용하는 대신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>
Table Export - HTML 테이블을 xlsx, xls, csv 및 txt 파일로 내보내기 위한 간단하고 구현이 용이한 라이브러리.
이 라이브러리를 사용하려면 생성자를 호출하십시오.
new TableExport(document.getElementsByTagName("table"));
// OR simply
TableExport(document.getElementsByTagName("table"));
// OR using jQuery
$("table").tableExport();
테이블, 버튼 및 내보낸 데이터의 모양과 느낌을 사용자 정의하기 위해 추가 속성을 전달할 수 있습니다.자세한 내용은 이쪽
http://wsnippets.com/export-html-table-data-excel-sheet-using-jquery/ 이 링크를 클릭하면 문제가 해결될 수 있습니다.

다음 예시를 정리합니다.
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();
}
}
Jquery를 사용하는 가장 간단한 방법
이것만 추가해 주세요.
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel@v1.0.4/dist/tableToExcel.js"></script>
다음으로 Jquery 스크립트를 추가합니다.
<script type="text/javascript">
$(document).ready(function () {
$("#exportBtn1").click(function(){
TableToExcel.convert(document.getElementById("tab1"), {
name: "Traceability.xlsx",
sheet: {
name: "Sheet1"
}
});
});
});
</script>
그런 다음 HTML 버튼을 추가합니다.
<button id="exportBtn1">Export To Excel</button><br><br>
★★★★★★"exportBtn1" ID, "은 테이블 , "tab1"은 테이블 ID가 됩니다.
Shield와 같은 라이브러리를 사용할 수 있습니다.이를 위한 UI.
널리 사용되는 XML 형식과 XLSX 형식 모두에 대한 내보내기를 지원합니다.
상세한 것에 대하여는, http://demos.shieldui.com/web/grid-general/export-to-excel 를 참조해 주세요.
14년 6월 6일부터 11시 59분에 샘포스에 대한 답변에 대해:
엑셀 데이터를 더 크게 표시하기 위해 폰트 사이즈가 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);
}
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은 취득되는 컬럼 이름입니다.
다음 코드는 서드파티 라이브러리가 필요 없는 최신 Chrome, Edge, Firefox에서 작동합니다.
HTML
<button onclick="download_table_as_csv('MyTableID_Value');">Export as CSV</button>
Jscript
function download_table_as_csv(table_id, separator = ',') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
// Download it
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}
내 버전의 @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');
});
Very Easy Code
Follow this instruction
Create excel.php file in your localhost root directory and copy and past this code.
Like this
http://localhost/excel.php?fileName=excelfile&link=1
<!-- http://localhost/excel.php?fileName=excelfile&link=2 -->
<!DOCTYPE html>
<html>
<head>
<title>Export excel file from html table</title>
</head>
<body style="display:
<?php
if( $_REQUEST['link'] == 1 ){
echo 'none';
}
?>;
">
<!-- --------Optional-------- -->
Excel <input type="radio" value="1" name="exportFile">
Others <input type="radio" value="2" name="exportFile">
<button onclick="myFunction()">Download</button>
<br>
<br>
<!-- --------/Optional-------- -->
<table width="100%" id="tblData">
<tbody>
<tr>
<th>Student Name</th>
<th>Group</th>
<th>Roll No.</th>
<th>Class</th>
<th>Contact No</th>
</tr>
<tr>
<td>Bulbul Sarker</td>
<td>Science</td>
<td>1</td>
<td>Nine</td>
<td>01724....</td>
</tr>
<tr>
<td>Karim</td>
<td>Science</td>
<td>3</td>
<td>Nine</td>
<td>0172444...</td>
</tr>
</tbody>
</table>
</body>
</html>
<style>
table#tblData{
border-collapse: collapse;
}
#tblData th,
#tblData td{
border:1px solid #CCC;
text-align: center;
}
</style>
<script type="text/javascript">
/*--------Optional--------*/
function myFunction() {
let val = document.querySelector('input[name="exportFile"]:checked').value;
if(val == 1)
{
this.exportTableToExcel();
}
}
/*--------/Optional--------*/
function exportTableToExcel(){
let filename2 = "<?php echo $_REQUEST['fileName']; ?>";
let tableId = 'tblData';
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableId);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
let filename = filename2?filename2+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
</script>
<?php
if( $_REQUEST['link'] == 1 ){
echo '<script type="text/javascript">
exportTableToExcel();
</script>';
}
?>
HTML
<a onclick="download_to_excel()">Download</a>
<table id="tableId">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3">Data Not Found</td>
</tr>
</tbody>
</table>
자바스크립트
function download_to_excel()
{
var tab_text="<table><tr>";
var textRange = '';
var j=0;
var tab = document.getElementById('tableId'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text += tab.rows[j].innerHTML+"</tr>";
}
tab_text +="</table>";
var a = document.createElement('a');
var data_type = 'data:application/vnd.ms-excel';
a.href = data_type + ', ' + encodeURIComponent(tab_text);
//setting the file name
a.download = 'file_name.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
}
언급URL : https://stackoverflow.com/questions/22317951/export-html-table-data-to-excel-using-javascript-jquery-is-not-working-properl
'programing' 카테고리의 다른 글
| @testable 사용 시 '모듈이 테스트용으로 컴파일되지 않았습니다' (0) | 2023.04.09 |
|---|---|
| 텍스트 선택 강조 표시를 비활성화하는 방법 (0) | 2023.04.09 |
| 문자열/문자의 벡터를 연결합니다. (0) | 2023.04.09 |
| 인수가 이 문자열과 같으면 이 문자열과 같은 변수를 정의합니다. (0) | 2023.04.09 |
| iPhone은 사용할 수 없습니다.장치를 다시 연결하십시오. (0) | 2023.04.09 |