圖片導出到Excel,圖片的路徑得調整一下,
把
<img src="1.jpg" id="img1" />
改為:
<img src="http://localhost:2079/%E6%B5%8B%E8%AF%951/1.jpg" />
這樣Excel導出的時候就能包含圖片了,但不是完美的解決方案。
導出注意事項:
- 圖片並不是實實在在存入Excel中的,應該僅僅只是存的圖片路徑
- 圖片的src地址必須是完整的,需要包含http這些,路徑是全的
- wps打開Excel應該有緩存這些圖片,所以即使把服務器關閉了,不能訪問圖片了,wps依然能展示圖片
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table id="targetTable">
<thead>
<tr>
<td>序號</td>
<td>圖片</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<img src="1.jpg" id="img1" />
</td>
</tr>
<tr>
<td>2</td>
<td>
<img src="http://localhost:2079/%E6%B5%8B%E8%AF%951/1.jpg" />
</td>
</tr>
<tr>
<td>3</td>
<td>
<img src="http://localhost:2079/%E6%B5%8B%E8%AF%951/3.jpg" style="width: 200px;" />
</td>
</tr>
<tr>
<td>4</td>
<td>
<img src="http://183.66.231.18:8084/Content/img/log.png" style="width: 100px;" />
</td>
</tr>
</tbody>
</table>
<a id="exportExcel" href="javascript:;">導出Excel</a>
<input type="button" id="btn1" value="btn1" />
<script src="//cdn.bootcss.com/jquery/2.2.1/jquery.min.js"></script>
<script>
//https://github.com/smileyby/js-table-excel
/**
* 將html的table轉成Excel的data協議類型數據,不支持ie
* table 是HTML DOM Document 對象
× name 是sheet的名稱
*/
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><meta http-equiv="Content-type" content="text/html;charset=UTF-8" /><!--[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>',
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) {
var ctx = {
worksheet: name || 'Worksheet',
table: table.innerHTML
}
return uri + base64(format(template, ctx));
}
})();
$(function () {
$('#exportExcel').on('click', function () {
var $this = $(this);
//設定下載的文件名及后綴
$this.attr('download', 'excelName.xls');
//設定下載內容
$this.attr('href', tableToExcel($('#targetTable')[0], 'excelName'));
});
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
var dataURL = canvas.toDataURL("image/" + ext);
return dataURL;
}
$("#btn1").click(function () {
var src = "1.jpg";
var image = new Image();
image.src = src;
image.onload = function () {
var base64 = getBase64Image(image);
console.log(base64);
$("#img1").attr("src", base64);
}
});
});
</script>
</body>
</html>
