Javascript를 사용하여 HTML 테이블을 Excel로 내보내기
내보내고 있다HTML
을 위해 식탁에 올리다.xls
포암트내보내기 후 Libre Office에서 열면 정상적으로 동작하지만 Microsoft Office에서도 빈 화면이 열립니다.
나는 원하지 않는다.jquery
솔루션 제공javascript
솔루션.제발 도와주세요.
function fnExcelReport() {
var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange;
var j = 0;
tab = document.getElementById('table'); // 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 id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();"> EXPORT
</button>
<table id="table">
<thead>
<tr>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<td>31</td>
<td>32</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>41</td>
<td>42</td>
<td>43</td>
<td>44</td>
</tr>
</tbody>
</table>
2016년 7월 12일, Microsoft는 Microsoft Office의 보안 업데이트를 추진했습니다.이 업데이트의 효과 중 하나는 보호 모드에서는 열 수 없기 때문에 신뢰할 수 없는 도메인의 HTML 파일이 Excel에 의해 열리지 않도록 하는 것입니다.
또한 레지스트리 설정에서는 Excel이 .X로 파일을 열 수 없습니다.내용이 공식 XLS 파일 형식과 일치하지 않는 LS 파일 확장자. 단, 기본값은 '거부'가 아닌 '경고'입니다.
이 변경 전에는 HTML 데이터를 XLS 확장자를 가진 파일에 저장할 수 있었고 Excel은 파일을 올바르게 열었습니다. 사용자 값에 따라 파일이 Excel 형식과 일치하지 않음을 먼저 경고할 수 있습니다.ExtensionHardening
레지스트리 키(또는 관련 설정 값)를 지정합니다.
Microsoft 에서는, 새로운 동작에 관한 기술 자료를 작성해, 몇개의 회피책을 제안했습니다.
이전에 HTML 파일을 XLS로 내보내는 데 의존했던 몇몇 웹 어플리케이션에서 업데이트 결과 문제가 발생했습니다.Sales Force가 그 예입니다.
2016년 7월 12일 이전의 답변 및 이와 유사한 질문에 대한 답변은 이제 무효가 될 수 있습니다.
원격 데이터에서 브라우저로 생성된 파일은 이 보호의 대상이 되지 않으며 신뢰할 수 없는 원격 소스에서 파일을 다운로드하는 데 방해가 될 뿐입니다.따라서 하나의 가능한 방법은 .X를 생성하는 것입니다.LS 라벨이 부착된 HTML 파일.
물론 다른 하나는 유효한 XLS 파일을 생성하는 것입니다.이 파일은 Excel에서 보호 모드로 열립니다.
업데이트: Microsoft는 이 동작을 수정하기 위한 패치를 릴리스했습니다.https://support.microsoft.com/en-us/kb/3181507
SheetJS가 딱 맞는 것 같아요.
테이블을 Excel 파일로 내보내려면 이 링크의 코드(시트와 함께)를 사용하십시오.JS)
콘센트에 꽂기만 하면table
요소 아이디export_table_to_excel
데모 참조
CSV 형식이 적절한 경우는, 다음의 예를 참조해 주세요.
- 네... 방금 댓글 봤는데 몸에 안 좋대요.코딩하기 전에 읽는 법을 배우지 못한 제 잘못이에요.
CSV는 Excel에서 처리할 수 있는 것으로 알고 있습니다.
function fnExcelReport() {
var i, j;
var csv = "";
var table = document.getElementById("table");
var table_headings = table.children[0].children[0].children;
var table_body_rows = table.children[1].children;
var heading;
var headingsArray = [];
for(i = 0; i < table_headings.length; i++) {
heading = table_headings[i];
headingsArray.push('"' + heading.innerHTML + '"');
}
csv += headingsArray.join(',') + ";\n";
var row;
var columns;
var column;
var columnsArray;
for(i = 0; i < table_body_rows.length; i++) {
row = table_body_rows[i];
columns = row.children;
columnsArray = [];
for(j = 0; j < columns.length; j++) {
var column = columns[j];
columnsArray.push('"' + column.innerHTML + '"');
}
csv += columnsArray.join(',') + ";\n";
}
download("export.csv",csv);
}
//From: http://stackoverflow.com/a/18197511/2265487
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();">EXPORT
</button>
<table id="table">
<thead>
<tr>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<td>31</td>
<td>32</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>41</td>
<td>42</td>
<td>43</td>
<td>44</td>
</tr>
</tbody>
</table>
이것을 머리에 추가해 주세요.
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
이를 javascript로 추가합니다.
<script type="text/javascript">
var tableToExcel = (function() {
var uri = '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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{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]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
Jfiddle : http://jsfiddle.net/cmewv/537/
이거 먹어봐
<table id="exportable">
<thead>
<tr>
//headers
</tr>
</thead>
<tbody>
//rows
</tbody>
</table>
이에 대한 스크립트
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
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.xls`, // 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.xls`, // 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
내보내기를 다운로드합니다.xls 파일
이것이 누군가에게 도움이 되기를 바랍니다:-)
<hrml>
<head>
<script language="javascript">
function exportF() {
//Format your table with form data
document.getElementById("input").innerHTML = document.getElementById("text").value;
document.getElementById("input1").innerHTML = document.getElementById("text1").value;
var table = document.getElementById("table");
var html = table.outerHTML;
var url = 'data:application/vnd.C:\\Users\WB-02\desktop\Book1.xlsx,' + escape(html); // Set your html table into url
var link = document.getElementById("downloadLink");
link.setAttribute("href", url);
link.setAttribute("download", "export.xls"); // Choose the file name
link.click(); // Download your excel file
return false;
}
</script>
</head>
<body>
<form onsubmit="return exportF()">
<input id="text" type="text" />
<input id="text1" type="text" />
<input type="submit" />
</form>
<table id="table" style="display: none">
<tr>
<td id="input">
<td id="input1">
</td>
</tr>
</table>
<a style="display: none" id="downloadLink"></a>
</body>
</html>
열이 너무 많은 경우 이 코드를 사용해 보십시오.쉽게 쪼개질 수 있어요.
function iterate( tab, startIndex , rowCount){
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
J=startIndex;
for(j = startIndex ; j < rowCount ; 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));
}
function fnExcelReport()
{
var indirilecekSayi = 250;
var toplamSatirSayisi = 0;
var baslangicSAyisi = 0;
var sonsatirsayisi = 0;
tab = document.getElementById('myTable'); // id of table
var maxRowCount = tab.rows.length;
toplamSatirSayisi = maxRowCount;
sonsatirsayisi=indirilecekSayi;
var kalan = toplamSatirSayisi % indirilecekSayi;
var KalansızToplamSatir=ToplamSatirSayisi-kalan;
var kacKati=Tsh / indirilecekSayi;
alert(maxRowCount);
alert(kacKati);
for (let index = 0; index <= kacKati; index++) {
if (index==kacKati) {
baslangicSAyisi =sonsatirsayisi;
sonsatirsayisi=sonsatirsayisi+kalan;
iterate(tab, baslangicSAyisi, sonsatirsayisi);
}else{
iterate(tab , baslangicSAyisi , sonsatirsayisi);
baslangicSAyisi=sonsatirsayisi;
sonsatirsayisi=sonsatirsayisi+indirilecekSayi;
if(sonsatirsayisi>ToplamSatirSayisi){
sonsatirsayisi=baslangicSAyisi;
}
}
}
}
언급URL : https://stackoverflow.com/questions/38748214/exporting-html-table-to-excel-using-javascript
'programing' 카테고리의 다른 글
하나의 파일을 제외한 모든 파일 이동 (0) | 2023.04.17 |
---|---|
Swift를 사용하여 iOS에서 프로그래밍 방식으로 설정하는 방법 (0) | 2023.04.17 |
ASCII 파일 전체를 C++ std:: 문자열로 읽습니다. (0) | 2023.04.17 |
JavaScript에서는 큰따옴표와 작은따옴표가 서로 호환됩니까? (0) | 2023.04.17 |
Bash 변수에서 공백을 잘라내는 방법 (0) | 2023.04.12 |