Merhaba arkadaşlar bu makalemde html table kullanarak excel çıktısı almayı göstereceğim
Sayfanıza 1 tane table Bir tanede gizli a etiketi koyunuz.
<a id="excelBtn" href="#" style="display:none;">Excel</a>
<table id="table">
<tr>
<th>
ID
</th>
<th>Ad</th>
<th>Soyad</th>
<th></th>
</tr>
<tr>
<td>
1
</td>
<td>John</td>
<td>Doe</td>
<td><a href="#" class="dontShowThis">DETAYLAR</a></td>
</tr>
<tr>
<td>
2
</td>
<td>Jane</td>
<td>Doe</td>
<td><a href="#" class="dontShowThis">DETAYLAR</a></td>
</tr>
</table>
Sonrasında aşağıdaki kodları kullanınız.
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var excelFromHtmlTable = (function () {
var uri = 'data:application/vnd.ms-excel;charset=UTF-8;base64,',
template = function (sheetName) {
return '<html xmlns:v="urn:schemas-microsoft-com:vml"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><meta http-equiv=Content-Type content="text/html; charset=UTF-8"><meta name=ProgId content=Excel.Sheet><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>' + sheetName + '</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border=1>{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, filename, removeAny="") {
if (!table.nodeType) table = document.getElementById(table);
if (removeAny!="") { //Don't show custom classes like inputs or selects
$("." + removeAny).remove();
}
var ctx = { table: table.innerHTML }
document.getElementById("excelBtn").href = uri + base64(format(template(name), ctx));
document.getElementById("excelBtn").download = filename;
document.getElementById("excelBtn").click();
}
})();
$(document).ready(function () {
excelFromHtmlTable("table", "sheetAdi", "excelAdi","dontShowThis");
});
</script>
excelFromHtmlTable methodu 4 parametre alıyor.
table: Excel'e basılacak table'ın id'si
name: Excel içinde açılacak sayfanın adı
filename: Excel dosya adı
removeAny: Excel'de görünmesini istemediğiniz alanlar. (Input, Select) gibi excele alırken bunlarıda basıyor. Kaldırmak istiyorsanız hepsini aynı class'ı verip method'ta kullanabilirsiniz
Makale örneğini indirmek için tıklayınız.
İyi Kodlar!